<?php
require_once('config.php');
$page_title ="New ID Card";
// 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>
  <section class="section mt-4">
    <div class="row">
      <div class="col-lg-4">
        <div class="bg-white rounded-2 p-3">
          <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_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>
      </div>
            <style media="screen">
        @font-face {
            font-family: 'Canvamahamudfutureit';
            font-style: normal;
            font-weight: 400;
            src: url(../uploads/id-card/fonts/canva-sans-regular.otf) format('opentype');
        }
        .front_tt_canvas,
        .back_tt_canvas{
            font-family: 'Canvamahamudfutureit', sans-serif;
            background: white;
            width: 300px;
            margin: auto;
            height: 476px;
            overflow: hidden;
            position: relative;
        }
        .mahamudfutureit_idcard_photo {
            width: 120px !important;
            height: 130px;
            position: absolute;
            top: 108px;
            object-fit: cover;
            left: 90px;
        }
        .mahamudfutureit_id_bg {
          width: 100%;
          height: 100%;
        }
.mahamudfutureit_idcard_name {
    font-size: 18px;
    letter-spacing: -1px;
    position: absolute;
    top: 267px;
    font-family: 'Canvamahamudfutureit', sans-serif;
    font-weight: bolder;
    width: 225px;
    right: 42px;
    color: #080808;
    text-align: center;
}
        .mahamudfutureit_idcard_designation {
            font-family: 'Canvamahamudfutureit', sans-serif;
            font-size: 16px;
            font-weight: bold;
            position: absolute;
            top: 335px;
            right: 44px;
            width: 228px;
            color: #ffffff;
            text-align: center;
        }

        .mahamudfutureit_region_card {
          font-size: 15px;
          position: absolute;
          top: 358px;
          left: 132px;
          font-size: bold !important;
        }
.mahamudfutureit_idcard_cardno {
    font-size: 15px;
    position: absolute;
    top: 176px;
    left: 85px;
    font-weight: bold;
    color: #0b0a0a;
}
            span.mahamudfutureit_idcard_nid {
            position: relative;
            top: -91px;
            font-size: 13px;
            color: white;
            left: 2px;
        }
        .mahamudfutureit_idcard_mobile {
            font-size: 15px;
            position: absolute;
            top: 157px;
            left: 95px;
            color: #100e0e;
            font-weight: bold;
        }
        .mahamudfutureit_idcard_blood {
            font-size: 15px;
            position: absolute;
            top: 138px;
            left: 127px;
            color: #080808;
            font-weight: bold;
        }       
        .mahamudfutureit_bg_dates {
          background-color: black;
          padding: 7px 15px 1px 15px;
          position: absolute;
          top: 206px;
          left: 82px;
        }
        
        .mahamudfutureit_idcard_exp_con {
            top: 117px;
            font-size: 15px;
            color: #000000;
            position: absolute;
            left: 54%;
            transform: translateX(-50%);
            font-weight: bold;
        }
        .mahamudfutureit_idcard_issue_con {
            top: 98px;
            font-size: 16px;
            color: #000000;
            position: absolute;
            left: 53%;
            transform: translateX(-50%);
            font-weight: bold;
        }    
                            
        .mahamudfutureit_idcard_qrcode {
            width: 63px;
            height: 67px;
            position: absolute;
            top: 393px;
            left: 219px;
            background: white;
            padding: 2px;
        }
      </style>
      <div class="col-lg-8">
        <div class="row g-3">
          <div class="col-md-6">
            <div class="front_tt_canvas" id="Front">
              <img class="mahamudfutureit_id_bg" src="../uploads/id-card/background/newsf.png" alt="Back Part">
              <img class="mahamudfutureit_idcard_photo w-100" src="" alt="Photo">
              <h1 class="mahamudfutureit_idcard_name">MAHAMUD FUTURE IT</h1>
              <h2 class="mahamudfutureit_idcard_designation">Founder & CEO</h2>
          </div>
          </div>
          <div class="col-md-6">
            <div class="back_tt_canvas" id="Back">
               <div class="back_tt_canvas" id="mahamudfutureitIDcard2">
              <img class="mahamudfutureit_id_bg" src="../uploads/id-card/background/newsb.png" alt="Back Part">
              <h5 class="mahamudfutureit_idcard_issue_con"><span class="mahamudfutureit_idcard_issue"></span> </h5>
              <h5 class="mahamudfutureit_idcard_exp_con"><span class="mahamudfutureit_idcard_exp"></span> </h5> 
               <h5>Blood Group : <span class="mahamudfutureit_idcard_blood"></span> </h5>
               <h5>Card No : CARD<span class="mahamudfutureit_idcard_cardno"></span> </h5>
                  <h5>Mobile Number: <span class="mahamudfutureit_idcard_mobile"></span> </h5>
            </div>
            </div>
          </div>
          <div class="col-12 text-center">
              <button id="generateBtn" onclick="captureAndDownload()" class="btn btn-success"> 
                <span class="btn-text">Generate Card</span>
                <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
            </button>
          </div>
      </div>
    </div>
  </section>
</main>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script type="text/javascript">
async function captureAndDownload() {
    const btn = document.getElementById("generateBtn");
    const btnText = btn.querySelector(".btn-text");
    const spinner = btn.querySelector(".spinner-border");

    // Show loading
    btn.disabled = true;
    btnText.textContent = "Processing...";
    spinner.classList.remove("d-none");

    try {
        const elementIds = ["Front", "Back"];

        for (let i = 0; i < elementIds.length; i++) {
            const captured = await captureElementAsBlob(elementIds[i]);

            if (captured) {
                downloadBlob(captured.blob, captured.filename);
                console.log(`✅ Downloaded: ${captured.filename}`);
            } else {
                console.warn(`⚠️ Failed to capture: ${elementIds[i]}`);
            }
        }

        // Restore button after success
        btnText.textContent = "Downloaded Successfully";
        btn.classList.add("btn-success");
        spinner.classList.add("d-none");

        setTimeout(() => {
            btn.disabled = false;
            btnText.textContent = "Generate Card";
            btn.classList.remove("btn-success");
        }, 2000);

    } catch (error) {
        console.error("💥 Capture error:", error);
        btn.disabled = false;
        btnText.textContent = "Retry Generate Card";
        btn.classList.add("btn-danger");
        spinner.classList.add("d-none");
    }
}

// Helper: Capture element as image
async function captureElementAsBlob(elementId, filenamePrefix = "ID_CARD") {
    const element = document.getElementById(elementId);
    if (!element) return null;

    element.style.pointerEvents = "none";

    const images = element.getElementsByTagName("img");
    await Promise.all(Array.from(images).map(async (img) => {
        if (!img.src.startsWith("data:")) {
            const response = await fetch(img.src);
            const blob = await response.blob();
            const reader = new FileReader();
            await new Promise(resolve => {
                reader.onloadend = () => { img.src = reader.result; resolve(); };
                reader.readAsDataURL(blob);
            });
        }
    }));

    await Promise.all(Array.from(images).map(img =>
        img.complete ? Promise.resolve() : new Promise(resolve => img.onload = resolve)
    ));

    element.style.pointerEvents = "";

    const canvas = await html2canvas(element, {
        backgroundColor: "transparent",
        scale: 4
    });

    const imageData = canvas.toDataURL("image/png");
    const blob = await (await fetch(imageData)).blob();

    return {
        blob,
        filename: `${filenamePrefix}_${elementId}.png`
    };
}

// ✅ Auto Download Function
function downloadBlob(blob, filename) {
    const link = document.createElement("a");
    const url = URL.createObjectURL(blob);

    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();

    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}
</script>



<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/placeholder/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 (skip date fields)
  const selectAuthor = document.getElementById("select_author");
  if (selectAuthor) {
    selectAuthor.addEventListener("change", function () {
      const selected = this.options[this.selectedIndex];

      Object.keys(fieldMap).forEach(id => {
        // Skip the date fields so they don't get overwritten
        if (id === "author_cexpdate" || id === "author_cissuedate") return;

        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'); ?>
