<?php
require_once('config.php');
include '../lib/phpqrcode-master/qrlib.php'; // Include QR library

// Delete Card
if (isset($_GET['delid'])) {
  $id_for_delete = $_GET['delid'] ;

  $card_save_path = '../uploads/id-card/';

  $card_front = $card_save_path.getSingleValue('mahamudfutureit_idcard', 'CardID', $id_for_delete, 'CardFront');
  $card_back = $card_save_path.getSingleValue('mahamudfutureit_idcard', 'CardID', $id_for_delete, 'CardBack');

  // Delete Temp Files
  if (file_exists($card_front)) { unlink($card_front); }
  if (file_exists($card_back)) { unlink($card_back); }

  if (deleteData('mahamudfutureit_idcard', 'CardID', $id_for_delete)){
    header("Location:writer-id-cards.php");
    exit;
  }else {
    $tt_alert = ttAlert('danger', 'Something went wrong to delete Card !');
  }
}

//  Add New Card
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  // Have Loaded Photo
  if ($_POST['author_photo_preloaded'] !='') {
    $author_photo_loaded = '../uploads/public_files/'.$_POST['author_photo_preloaded'];
  }else {
    $author_photo_loaded = '';
  }
  // Upload Author Photo For ID Card
  if (isset($_FILES['author_photo']) && $_FILES['author_photo']['error'] == 0) {

    $get_old_file_ext = pathinfo($_FILES['author_photo']['name'], PATHINFO_EXTENSION);

    if ($get_old_file_ext == 'jpeg' || $get_old_file_ext == 'png' || $get_old_file_ext == 'jpg') {
      $tempUploadDir = '../uploads/id-card/temp/';

      // Set new file name
      $fileNameAuthor = 'temp_'. md5(uniqid().time()) .'.'. $get_old_file_ext;
      $targetFilePathAuthor = $tempUploadDir . $fileNameAuthor;

      if (move_uploaded_file($_FILES['author_photo']['tmp_name'], $targetFilePathAuthor)) {
          $author_id_photo = $targetFilePathAuthor;
      } else {
          $author_id_photo = $author_photo_loaded;
      }
    }else {
        $author_id_photo = $author_photo_loaded;
    }
  } else {
      $author_id_photo = $author_photo_loaded;
  }
  // Have Author Photo Then Create User Id Card
  if ($author_id_photo !='') {

    $font_regular = '../uploads/id-card/fonts/OpenSans-Regular.ttf'; // Your TTF font
    $font_medium = '../uploads/id-card/fonts/OpenSans-Medium.ttf'; // Your TTF font
    $font_bold = '../uploads/id-card/fonts/OpenSans-Bold.ttf'; // Your TTF font

    /*************************/
    // Start Front Part
    /*************************/
    $front_background = '../uploads/id-card/background/f_background.jpg'; // Your background image

    // First, create the background image
    $front_part = createImage($front_background);

    // Add image -> background, photo_to_add, top_position, left_position, widht, height, border, border_color
    $front_part = addImageToImage( $front_part, $author_id_photo, 504, 441, 813, 920, 100, [255, 255, 255] );

    if ($_POST['author_name'] !='') {
      // Add Text -> background, text_to_add, select_font, font_size, font_color,  left_position, top_position
      $front_part = addTextToImage($front_part, strtoupper($_POST['author_name']) , $font_bold, 70, [0, 0, 0], 460, 1460);
    }

    //
    // if ($_POST['author_designation'] !='') {
    //   // Add Text -> background, text_to_add, select_font, font_size, font_color,  left_position, top_position
    //   $front_part = addTextToImage($front_part, strtoupper($_POST['author_designation']), $font_bold, 48, [191, 39,  44], 'center', 1310);
    // }
    //
    if ($_POST['author_card_no'] !='') {
      // Add Text -> background, text_to_add, select_font, font_size, font_color,  left_position, top_position
      $front_part = addTextToImage($front_part, strtoupper($_POST['author_card_no']), $font_bold, 70, [0, 0, 0], 814, 1940);
    }
    //
    // if ($_POST['author_nid'] !='') {
    //   // Add Text -> background, text_to_add, select_font, font_size, font_color,  left_position, top_position
    //   $front_part = addTextToImage($front_part, strtoupper($_POST['author_nid']), $font_bold, 30, [0, 0, 0], 884, 1558);
    // }
    //
    if ($_POST['author_blood'] !='') {
      // Add Text -> background, text_to_add, select_font, font_size, font_color,  left_position, top_position
      $front_part = addTextToImage($front_part, strtoupper($_POST['author_blood']), $font_bold, 70, [191, 39,  44], 814, 2200);
    }
    //
    if ($_POST['author_number'] !='') {
      // Add Text -> background, text_to_add, select_font, font_size, font_color,  left_position, top_position
      $front_part = addTextToImage($front_part, strtoupper($_POST['author_number']), $font_bold, 70, [0, 0, 0], 814, 2080);
    }
    //
    // if ($_POST['author_qrtext'] !='') {
    //   $qr_link = $_POST['author_qrtext'];
    // }else {
    //   $qr_link = $site_domain;
    // }
    //
    // $qr_profile_code = '../uploads/id-card/temp/temp_'. md5(uniqid().time()) .'.png'; // Generate a   filename
    // QRcode::png($qr_link, $qr_profile_code, 'H', '10', 2); // Create and save QR code
    //
    // // Add image -> background, photo_to_add, top_position, left_position, widht, height, border, border_color
    // $front_part = addImageToImage( $front_part, $qr_profile_code, 1470, 200, 280, 280, 0, [192, 39, 45] );

    $card_save_path = '../uploads/id-card/';

    // Save the final image
    $save_front_name = 'mahamudfutureit.com_Front_'.$_POST['author_card_no'].'_'.md5(uniqid().time()).'.jpg';
    $save_front = $card_save_path.$save_front_name;
    saveFinalImage($front_part, $save_front);

    /*****************************/
    // Start Front Part
    /*****************************/
    $back_background = '../uploads/id-card/background/b_background.jpg'; // Your background image

    // First, create the background image
    $back_part = createImage($back_background);

    if ($_POST['author_cissuedate'] !='') {
      // Add Text -> background, text_to_add, select_font, font_size, font_color,  left_position, top_position
      $back_part = addTextToImage($back_part, strtoupper($_POST['author_cissuedate']), $font_medium, 45, [0, 0, 0], 825, 1388);
    }

    if ($_POST['author_cexpdate'] !='') {
      // Add Text -> background, text_to_add, select_font, font_size, font_color,  left_position, top_position
      $back_part = addTextToImage($back_part, strtoupper($_POST['author_cexpdate']), $font_medium, 45, [0, 0, 0], 825, 1478);
    }

    if ($_POST['author_card_no'] !='') {
      // Add Text -> background, text_to_add, select_font, font_size, font_color,  left_position, top_position
      $back_part = addTextToImage($back_part, strtoupper($_POST['author_card_no']), $font_medium, 45, [0, 0, 0], 825, 1568);
    }

    // Save the final image
    $save_back_name = 'mahamudfutureit.com_Back_'.$_POST['author_card_no'].'_'.md5(uniqid().time()).'.jpg';
    $save_back = $card_save_path.$save_back_name;
    saveFinalImage($back_part, $save_back);

    // Delete Temp Files
    if (file_exists($qr_profile_code)) { unlink($qr_profile_code); }
    if (file_exists($targetFilePathAuthor) && isset($targetFilePathAuthor)) { unlink($targetFilePathAuthor); }
    // Add ID Card To Database
    $post_form_data = array(
      "CardUser"=>$_POST['select_author'],
      "CardUserName"=>$_POST['author_name'],
      "CardNo"=>$_POST['author_card_no'],
      "CardIssue"=>$_POST['author_cissuedate'],
      "CardValidity"=>$_POST['author_cexpdate'],
      "CardCreated"=>$the_time,
      "CardFront"=>$save_front_name,
      "CardBack"=>$save_back_name,
      "CardAdmin"=>getSingleValue('admin_user', 'admin_security_key', $_COOKIE['Google_SLKA'] , 'admin_id'),
    );
    // Insert Database
    if (InsertData('mahamudfutureit_idcard', $post_form_data)) {
     header("Location:writer-id-cards.php");
    }else {
      $tt_alert = ttAlert('danger', 'Something went wrong to Store ID Card Data !');
    }
  }else {
    $tt_alert = ttAlert('danger', 'Invalid Author Image');
  }
}

// Include Heaser File
require_once('inc/header.php');

?>
<main id="main" class="main ">
  <div class="row">
    <div class="col-6 align-items-center">
      <div class="pagetitle mb-0">
        <h1><?php echo $page_title ?></h1>
      </div>
    </div>
  </div>
  <?php
  if (!extension_loaded('gd')) {
    ?>
    <div class="alert alert-warning my-2">
      GD extension is requered for Create ID Card.
    </div>
    <?php
  }
  echo $tt_alert ?? '';
  ?>
  <section class="section mt-4">
    <div class="row">
      <div class="col-4">
        <form class="bg-white rounded-2 p-3" action="" method="post" enctype="multipart/form-data" >
          <h5>Issue Card</h5>
          <?php
            $today = date('Y-m-d');
            $expiry = date('Y-m-d', strtotime('+1 year'));
          ?>
          <div class="form-group mb-3">
            <label class="form-label" for="select_author">Select Author</label>
            <select class="form-select " name="select_author" id="select_author">
              <option value="">Select Author</option>
              <?php
                $tt_writers = showAllttdata("tt_accounts", "ORDER BY  UserID  ASC");
                foreach ($tt_writers as $the_author) {
                  ?>
                  <option value="<?php echo htmlentities($the_author['UserID'], ENT_QUOTES, 'utf-8'); ?>"
                            data-author_name="<?php echo htmlentities($the_author['UserNameEN'], ENT_QUOTES, 'utf-8'); ?>"
                            data-author_designation="<?php echo htmlentities($the_author['UserDesignationEn'], ENT_QUOTES, 'utf-8'); ?>"
                            data-author_photo_preloaded="<?php echo $the_author['PhotoFile'] ?>"
                            data-author_card_no="<?php echo htmlentities($the_author['UserID'], ENT_QUOTES, 'utf-8'); ?>"
                            data-author_blood="<?php echo htmlentities($the_author['UserBlood'], ENT_QUOTES, 'utf-8'); ?>"
                            data-author_number="<?php echo htmlentities($the_author['UserMobile'], ENT_QUOTES, 'utf-8'); ?>"
                            data-author_nid="<?php echo htmlentities($the_author['UserNID'], ENT_QUOTES, 'utf-8'); ?>"
                            data-author_qrtext="<?php echo userProfile($the_author['UserID']) ?>">
                            <?php echo ($the_author['UserNameEN'] !='') ? $the_author['UserNameEN'] : $the_author['UserName'] ?>
                  </option>
                  <?php
                }
              ?>
            </select>
          </div>
          <img id="author_photo_preview" class="d-block m-auto" src="assets/img/default-avatar-icon.jpg" alt="Photo Preview" style=" max-width:150px; margin-top:10px;">

          <div class="form-group mb-3">
            <label class="form-label" for="author_name">Name  <span class="text-danger">*</span> </label>
            <input class="form-control" value="<?php echo $_POST['author_name'] ?>" type="text" name="author_name" id="author_name" required>
          </div>

          <div class="form-group mb-3">
            <label class="form-label" for="author_designation">Designation <span class="text-danger">*</span></label>
            <input class="form-control" value="<?php echo $_POST['author_designation'] ?>" type="text" name="author_designation" id="author_designation" required>
          </div>

          <div class="form-group mb-3">
            <label class="form-label" for="author_photo">Photo (560x650px)</label>
            <input class="form-control" type="file" name="author_photo" id="author_photo" accept="image/*">
            <input class="form-control" type="hidden" name="author_photo_preloaded" id="author_photo_preloaded">
          </div>

          <div class="form-group mb-3">
            <label class="form-label" for="author_card_no">Card No. <span class="text-danger">*</span></label>
            <input class="form-control" value="<?php echo $_POST['author_card_no'] ?>" type="text" name="author_card_no" id="author_card_no" required>
          </div>

          <div class="form-group mb-3">
            <label class="form-label" for="author_nid">NID No.</label>
            <input class="form-control"  value="<?php echo $_POST['author_nid'] ?>" type="text" name="author_nid" id="author_nid">
          </div>

          <div class="form-group mb-3">
            <label class="form-label" for="author_number">Phone Number</label>
            <input class="form-control" value="<?php echo $_POST['author_number'] ?>" type="text" name="author_number" id="author_number">
          </div>

          <div class="form-group mb-3">
            <label class="form-label" for="author_blood">Blood Group</label>
            <input class="form-control" value="<?php echo $_POST['author_blood'] ?>" type="text" name="author_blood" id="author_blood">
          </div>

          <div class="form-group mb-3">
            <label class="form-label" for="author_cissuedate">Issue Date</label>
            <input class="form-control"  type="date" name="author_cissuedate" id="author_cissuedate" value="<?php echo (isset($_POST['author_cissuedate']) ? $_POST['author_cissuedate'] : $today) ?>" required>
          </div>

          <div class="form-group mb-3">
            <label class="form-label" for="author_cexpdate">Expiry Date</label>
            <input class="form-control"   type="date" name="author_cexpdate" id="author_cexpdate" value="<?php echo (isset($_POST['author_cexpdate']) ? $_POST['author_cexpdate'] : $expiry) ?>" required>
          </div>
          <div class="form-group mb-3">
            <label class="form-label" for="author_qrtext">QR Text (Profile Link)</label>
            <input class="form-control" value="<?php echo $_POST['author_qrtext'] ?>" type="text" name="author_qrtext" id="author_qrtext">
          </div>

          <button type="submit" class="btn btn-success w-100">Generate Card</button>
        </form>
      </div>
      <style media="screen">
        .front_tt_canvas,
        .back_tt_canvas{
          background: white;
          width: 300px;
          margin: auto;
          height: 476px;
          overflow: hidden;
          position: relative;
        }
      </style>
      <div class="col-8">
        <div class="row">
          <div class="col-md-6">
            <div class="front_tt_canvas">
              <img class="mahamudfutureit_idcard_photo w-100" src="" alt="Photo">
              <h1 class="mahamudfutureit_idcard_name">mahamudfutureit.com</h1>
              <h2 class="mahamudfutureit_idcard_designation">Founder & CEO</h2>
              <h5>Card No : <span class="mahamudfutureit_idcard_cardno"></span> </h5>
              <h5>NID No : <span class="mahamudfutureit_idcard_nid"></span> </h5>
              <h5>EXP Date : <span class="mahamudfutureit_idcard_exp"></span> </h5>

            </div>
          </div>
          <div class="col-md-6">
            <div class="back_tt_canvas">
              <h5>ISSUE Date : <span class="mahamudfutureit_idcard_issue"></span> </h5>
              <h5>Blood Group : <span class="mahamudfutureit_idcard_blood"></span> </h5>
              <h5>Mobile Number: <span class="mahamudfutureit_idcard_mobile"></span> </h5>
              <img class="mahamudfutureit_idcard_qrcode" src="" alt="Photo">
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
</main>
<script>
  // Map: form field ID → preview selector
  const fieldMap = {
    author_name: ".mahamudfutureit_idcard_name",
    author_designation: ".mahamudfutureit_idcard_designation",
    author_card_no: ".mahamudfutureit_idcard_cardno",
    author_nid: ".mahamudfutureit_idcard_nid",
    author_cexpdate: ".mahamudfutureit_idcard_exp",
    author_cissuedate: ".mahamudfutureit_idcard_issue",
    author_blood: ".mahamudfutureit_idcard_blood",
    author_number: ".mahamudfutureit_idcard_mobile",
    author_qrtext: ".mahamudfutureit_idcard_qrcode",
    author_photo_preloaded: ".mahamudfutureit_idcard_photo"
  };

  // Update preview function
  function updatePreview(id, value) {
    const selector = fieldMap[id];
    if (!selector) return;

    const element = document.querySelector(selector);

    if (id === "author_photo_preloaded") {
      if (value && value !== "") {
        element.src = "<?php echo $site_domain ?>uploads/public_files/" + value;
      } else {
        element.src = "assets/img/default-avatar-icon.jpg";
      }
    }
    else if (id === "author_qrtext") {
      if (value && value !== "") {
        const apiUrl = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + encodeURIComponent(value);
        fetch(apiUrl)
          .then(res => res.blob())
          .then(blob => {
            const reader = new FileReader();
            reader.onloadend = function () {
              element.src = reader.result; // Base64 image
            };
            reader.readAsDataURL(blob);
          });

      } else {
        element.src = "assets/img/default-qr.png";
      }
    }
    else {
      element.textContent = value;
    }
  }

  // Attach listeners for all fields
  Object.keys(fieldMap).forEach(id => {
    const input = document.getElementById(id);
    if (input) {
      input.addEventListener("input", function () {
        updatePreview(id, this.value);
      });
      // Initial load
      updatePreview(id, input.value);
    }
  });

  // Handle select dropdown (if exists)
  const selectAuthor = document.getElementById("select_author");
  if (selectAuthor) {
    selectAuthor.addEventListener("change", function () {
      const selected = this.options[this.selectedIndex];

      Object.keys(fieldMap).forEach(id => {
        const value = selected.getAttribute("data-" + id) || "";
        const input = document.getElementById(id);
        if (input) {
          input.value = value;
          updatePreview(id, value);
        }
      });
    });
  }
  // Handle new photo upload
  const photoInput = document.getElementById("author_photo");
  if (photoInput) {
    photoInput.addEventListener("change", function (event) {
      const file = event.target.files[0];
      const preview = document.querySelector(".mahamudfutureit_idcard_photo");

      if (file && file.type.startsWith("image/")) {
        const reader = new FileReader();
        reader.onload = function (e) {
          preview.src = e.target.result;
        };
        reader.readAsDataURL(file);
      } else {
        preview.src = "assets/img/default-avatar-icon.jpg";
      }
    });
  }
</script>


<?php require_once('inc/footer.php'); ?>
