<?php
require __DIR__ . '/db.php';

$id = intval($_GET['id'] ?? 0);
if ($id <= 0) { die("Invalid id"); }

$stmt = $conn->prepare("SELECT * FROM users WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();
if(!$data){ die("Data not found"); }

// QR validation URL (Pkey=uid, BruteForceKey=image filename)
$baseUrl = "https://online.csgb.gov.ct.tr.calismac.com/CIP/BasvuruAnaQRKODValidation/Validate/";
$validationUrl = $baseUrl
  . "?Ne=onizinbelgepdf"
  . "&BruteForceKey=" . urlencode(basename($data['image'] ?? ''))
  . "&Pkey=" . urlencode($data['uid'] ?? '');

$qrImgUrl = "https://api.qrserver.com/v1/create-qr-code/?size=260x260&data=" . urlencode($validationUrl);

// Fixed/defaults
$sex         = "E";
$nationality = "BANGLADEŞ/ BANGLADESH";
$occupation  = "Ekskavatör(Kazıma  Ve Yükleme) Operatörü";
$employer    = "KOOP SÜT";
$regNo       = "GY-03045";
$duration    = "1 YIL";

// Dates
$docDate     = $data['start'] ?? "";   // আপনার চাইলে approve/date কলাম হলে এখানে সেট করবেন
$startDate   = $data['start'] ?? "";
$endDate     = $data['end'] ?? "";
$printDate   = date("d.m.Y H:i:s");

$policeNumber = "2504595";
$appNumber = ($data['uid'] ?? '') . "/2026";

// user photo base url
$USER_IMAGE_BASE = "https://online.csgb.gov.ct.tr.calismac.com/CIP/BasvuruAnaQRKODValidation/Validate/uploads/";
?>
<!doctype html>
<html lang="tr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pre-permit Application</title>

<style>
  body{font-family:"Times New Roman", serif; background:#f2f2f2; margin:0; padding:18px;}
.sheet{
  width:210mm;            /* A4 width */
  min-height:297mm;       /* A4 height */
  margin:0 auto;
  background:#fff;
  color:#000;
  padding:12mm 12mm;      /* 🔴 একটু কম padding */
  box-sizing:border-box;
  position:relative;
}


  .center{text-align:center;}
  .bold{font-weight:700;}
  .small{font-size:12px;}
  .title1{font-size:18px; font-weight:700;}
  .title2{font-size:16px; font-weight:700;}
  .title3{font-size:14px; font-weight:700;}

  /* table base */
  table{width:100%; border-collapse:collapse; table-layout:fixed;}
  .t, .t th, .t td{border:2px solid #000;}
  .t th{padding:6px 8px; font-size:12px; vertical-align:top; text-align:left;}
  .t td{padding:8px 8px; font-size:13px; vertical-align:middle; font-weight:normal;}

  .sub{display:block; font-weight:700;}
  .en{display:block; font-weight:400; font-size:11px; margin-top:2px;}

  /* photo (no border) */
  .photo{
    max-width:100%;
    max-height:100%;
    width:auto;
    height:auto;
    display:block;
    margin:auto;
    object-fit:contain;
    border:none !important;
    outline:none !important;
    box-shadow:none !important;
    background:#fff;
  }

  .mt6{margin-top:6px;}
  .mt10{margin-top:10px;}
  .mt14{margin-top:14px;}
  .para{font-size:12px; line-height:1.25; margin-top:8px;}

  /* logo + watermark */
  .logoWrap{display:flex; justify-content:center; margin-bottom:6px;}
  .logo{width:70px; height:auto;}




  .content{position:relative; z-index:1;}

  /* QR */
  .qrBlock{margin-top:8px; text-align:center;}
  .qrImg{
    width:150px;
    height:150px;
    border:none !important;
    outline:none !important;
    box-shadow:none !important;
    display:block;
    margin:auto;
  }

  .attn{margin-top:8px; text-align:center; font-size:12px; line-height:1.25;}
  .attn .red{color:#c00; font-weight:700;}
  .footer{margin-top:8px; text-align:right; font-size:12px; font-weight:700;}

  /* Ministry approval */
  .ministryTitle{
    font-weight:700;
    font-size:14px;
    margin-top:10px;
    margin-bottom:4px;
  }
  .ministryTbl{table-layout:fixed;}
  .minDesc{font-size:12px; line-height:1.2; padding:6px 8px;}
  .minMainRow th, .minMainRow td{height:60px;} /* compact */
  .minLabel{width:10%;}
  .minDate{width:16%; text-align:center;}
  .minOffice{width:44%; font-size:12px;}
  .minStamp{width:15%; text-align:center; vertical-align:middle;}
  .minInternet{width:15%; text-align:center; font-weight:700;}
  .minStamp img{width:90px; display:block; margin:auto; border:none;}

  .minValidRow th, .minValidRow td{padding:6px 8px; vertical-align:middle;}
  .vLabel{font-weight:700; text-align:left; white-space:nowrap;}
  .vDate{text-align:center; white-space:nowrap; font-weight:normal;}




  /* base */
.ministryTbl{ table-layout:fixed; }

/* ===== VALIDITY TABLE WITH % WIDTH ===== */
.validityPercent{
  width:100%;
  border-collapse:collapse;
  table-layout:fixed;   /* 🔴 % width কাজ করার জন্য */
  margin-top:-2px;
}

.validityPercent th,
.validityPercent td{
  border:2px solid #000;
  padding:3px 5px;
  font-size:12px;       /* 🔴 ছোট font */
  white-space:nowrap;  /* 🔴 এক লাইনে */
  vertical-align:middle;
  overflow:hidden;     /* 🔴 অন্য column এ ঢুকবে না */
}

/* ===== COLUMN WIDTH CONTROL ===== */
/* এখানে % বদলালেই layout বদলাবে */



@media print{

  @page{
    size:A4;
    margin:6mm;          /* 🔴 margin কম */
  }

  body{
    margin:0;
    padding:0;
  }

  /* Scale entire sheet more aggressively */
  .sheet{
    transform:scale(1);   /* 🔴 0.92 → 0.88 */
    transform-origin:top left;
  }

  /* Reduce fonts globally */
  body, table, td, th{
    font-size:9px !important;
  }

  /* Reduce paddings */
  .t th,
  .t td{
    padding:3px 4px !important;
  }

  /* Titles smaller */
  .title1{ font-size:15px !important; }
  .title2{ font-size:13px !important; }
  .title3{ font-size:12px !important; }

  /* QR smaller + pull up */
  .qrImg{
    width:100px !important;
    height:100px !important;
  }

  .qrBlock{
    margin-top:4px !important;
  }

  .attn{
    font-size:9px !important;
    margin-top:4px !important;
  }

  .footer{
    font-size:9px !important;
    margin-top:4px !important;
  }

  /* FORCE no page break anywhere */
  *{
    page-break-before:avoid !important;
    page-break-after:avoid !important;
    page-break-inside:avoid !important;
  }

  /* Keep bottom section together */
  .printBottom{
    page-break-inside:avoid !important;
  }
}


</style>
</head>

<body>
<div class="sheet">
  

  <div class="content">

    <div class="logoWrap">
      <img class="logo" src="assets/logo.jpg" alt="logo">
    </div>

    <div class="center title1">ÇALIŞMA VE SOSYAL GÜVENLİK BAKANLIĞI</div>
    <div class="center title2">MINISTRY OF LABOUR AND SOCIAL SECURITY</div>
    <div class="center title3 mt6">Ön İzin Başvurusu/Pre-permit Application</div>
    <div class="center small">(Yurt Dışından Getirtilmek İstenen İşçi Listesi / The worker to be brought )</div>

    <div class="small mt10">
      <span class="bold">Note:</span> Bu form 3 (üç) Suret Olarak Düzenlenecektir.<br>
      <span class="bold">Note:</span> This form will be prepared in 3 (three) copies.
    </div>

    <!-- Application number block -->
    <table class="t mt10" style="width:auto; display:inline-table;">
      <tr>
        <th style="width:43.6mm">
          <span class="sub">Başvuru No</span>
          <span class="en">ApplicationNumber</span>
        </th>
        <td style="width:21mm"><b><?= htmlspecialchars($appNumber) ?></b></td>
      </tr>
    </table>

    <!-- Main worker table -->
    <table class="t" style="margin-top:-2px;">
      <tr>
        <th style="width:18%"><span class="sub">Adı-Soyadı</span><span class="en">Name-Surname</span></th>
        <th style="width:8%"><span class="sub">CinsiyEt</span><span class="en">Sex</span></th>
        <th style="width:14%"><span class="sub">DoğumTarihi</span><span class="en">Date of Birth</span></th>
        <th style="width:18%"><span class="sub">Uyruğu</span><span class="en">Nationality</span></th>
        <th style="width:12%"><span class="sub">PasaportNo</span><span class="en">PassportNo</span></th>
        <th style="width:20%"><span class="sub">Mesleği</span><span class="en">Occupation</span></th>
        <th style="width:10%"><span class="sub">Resim</span><span class="en">Photo</span></th>
      </tr>
      <tr>
        <td><?= htmlspecialchars($data['name'] ?? '') ?></td>
        <td class="center"><?= htmlspecialchars($sex) ?></td>
        <td class="center"><?= htmlspecialchars($data['birth'] ?? '') ?></td>
        <td><?= htmlspecialchars($nationality) ?></td>
        <td class="center"><?= htmlspecialchars($data['passport'] ?? '') ?></td>
        <td><?= htmlspecialchars($occupation) ?></td>
        <td class="center" style="height:92px; padding:6px;">
          <?php if(!empty($data['image'])): ?>
            <img class="photo" src="<?= $USER_IMAGE_BASE . htmlspecialchars($data['image']) ?>" alt="photo">
          <?php else: ?>
            <div class="small">No Photo</div>
          <?php endif; ?>
        </td>
      </tr>
    </table>

    <!-- Police approval -->
    <div class="bold mt14">POLİS GENEL MÜDÜRLÜĞÜ ONAYI / APPROVAL OF THE POLICE HEADQUARTERS</div>
    <div class="small mt6">
      Sayı/Number: <span class="bold"><?= htmlspecialchars($policeNumber) ?></span>
      &nbsp;&nbsp;
      Tarih/Date: <span class="bold"><?= htmlspecialchars($docDate) ?></span>
    </div>

    <div class="para">
      <span class="bold">Çalışma ve Sosyal Güvenlik Bakanlığı'na / To the Ministry of Labor and Social Security</span><br>
      Şu anda yurt dışında olan yukarıda Adı, Soyadı, Cinsiyeti, Uyruğu, Pasaport Numarası ve Mesleği yazılı yabancı uyruklu kişileri
      işyerimde istihdam etmek istediğimi ve KKTC'ye girişlerinden itibaren en geç 15 gün içerisinde Çalışma İzni işlemlerini başlatacağımı
      ve 30 gün içerisinde tamamlayacağımı beyan ederim. / I declare that I want to employ the foreign national whose information is written above,
      who is currently abroad, in my workplace, and that I will initiate the Work Permit procedures within 15 days at the latest after entering the TRNC
      and will complete it within 30 days.
    </div>

    <!-- Employer table -->
    <table class="t mt10">
      <tr>
        <th style="width:30%">İşveren:<br>Employeer:</th>
        <td style="width:25%"><?= htmlspecialchars($employer) ?></td>
        <th style="width:30%">Çalışma D. Tescil No:<br>LaborDepartment RegistrationNumber:</th>
        <td style="width:15%"><?= htmlspecialchars($regNo) ?></td>
      </tr>
      <tr>
        <th>İşveren Temsilcisi (varsa):<br>Employer Representative(ifany):</th>
        <td></td>
        <th>Çalışma İzin Süresi:<br>Work Permit Duration:</th>
        <td><?= htmlspecialchars($duration) ?></td>
      </tr>
      <tr>
        <th>Başvuru Tarihi:<br>Application Date:</th>
        <td><?= htmlspecialchars($docDate) ?></td>
        <th></th>
        <td></td>
      </tr>
    </table>

    <!-- Ministry approval -->
    <div class="ministryTitle">Bakanlık Onayı &nbsp;/&nbsp; Ministry Approval</div>

    <table class="t mt6 ministryTbl">
  <!-- Description -->
  <tr>
    <td colspan="5" class="minDesc">
      Yukarıdaki müracaat değerlendirilmiş ve formda adı yazılı işverenin yurt dışından işçi getirme talebi uygun bulunmuştur.
      The above application has been evaluated and the request of the employerwhose name iswrittenonthe formtobringworkersfromabroadhas beenfoundappropriate.
    </td>
  </tr>

  <!-- Main row (same widths as screenshot) -->
  <tr class="minMainRow">
    <td style="width:8%; text-align:left;">Tarih:<br>Date:</td>
    <td style="width:14%; text-align:center; padding-left:14px;">
      <?= htmlspecialchars($docDate) ?>
    </td>
    <td style="width:50%; font-size:10px;">
      Çalışma ve Sosyal Güvenlik Bakanlığı<br>
      Ministry of Labour and Social Security
    </td>
    <td style="width:18%; text-align:center; vertical-align:middle;">
      <img src="assets/stamp.jpg" alt="stamp" style="width:95px; border:none; display:block; margin:auto;">
    </td>
    <td style="width:16%; text-align:center; font-weight:700;">
      Internet
    </td>
  </tr>

</table>
<table class="t validityPercent">
  <tr>
    <!-- Column 1: Start label -->
    <td style="width:40%;" class="col-start-label">
     <b>Geçerlilik Başlangıç Tarihi/Validity Start Date:</b>
    </td>

    <!-- Column 2: Start date -->
    <td class="col-start-date" style="width:10%;">
      <?= htmlspecialchars($startDate) ?>
    </td>

    <!-- Column 3: End label -->
    <td class="col-end-label" style="width:32%;">
     <b>Geçerlilik Bitiş Tarihi/Expiration Date:</b>
    </td>

    <!-- Column 4: End date -->
    <td class="col-end-date style="width:8%;"">
      <?= htmlspecialchars($endDate) ?>
    </td>
  </tr>
</table>



<div class="printBottom">
  <div class="small mt10">
    Belgenin doğruluğunun teyidi için aşağıdaki karekodu okutun.<br/>
    Scan the QR code below to confirm the authenticity of the document.
  </div>

  <div class="qrBlock">
    <img class="qrImg" src="<?= htmlspecialchars($qrImgUrl) ?>" alt="qr">
  </div>

  <div class="attn">
    <span class="red">DİKKAT!</span> Bu belgenin KKTC'ye girişte Muhaceret polisine ibraz edilmesi zorunludur.<br>
    <span class="red">ATTENTION!</span> This Pre-permit document must be submitted to the immigration officer upon entry.
  </div>

  <div class="footer">
    Basım Tarihi/Print Date: <?= htmlspecialchars($endDate) ?> 20:15:33 (Form.ÇSB.Yİ.02)
  </div>
</div>


  </div>
</div>
</body>
</html>
