<?php
require_once __DIR__.'/db.php';
// require_once './header.php';

if(!isset($_SESSION["admin_id"])){
  require_student();
}

$attempt_id = (int)($_GET['attempt_id'] ?? 0);
$student_id = (int)$_SESSION['student_id'];

$row = $mysqli->query("
    SELECT a.*, date(a.completed_at) as completed_date, q.title, q.language, s.full_name
    FROM attempts a
    JOIN quizzes q ON q.id=a.quiz_id
    JOIN students s ON s.id=a.student_id
    WHERE a.id=$attempt_id
")->fetch_assoc();

if(!$row || $row['status']!=='completed'){
  die('Certificate unavailable.');
}

$totalMarks = $mysqli->query("
    SELECT SUM(b.marks)
    FROM questions a
    LEFT JOIN (
      SELECT question_id, MAX(marks) as marks
      FROM options GROUP BY question_id
    ) b ON a.id=b.question_id
    WHERE a.quiz_id=".$row['quiz_id']
)->fetch_row()[0];

$percent = $totalMarks ? round($row['marksObtained']*100/$totalMarks) : 0;
$title = $row['title'];
$marksObtained = $row['marksObtained'];

$certificateLang = $row['language'];
if($certificateLang=='urdu'){
  $name = urlencode($row['full_name']);
  $url = "https://inputtools.google.com/request?text=$name&itc=ur-t-i0-und&num=1";

  $response = file_get_contents($url);
  $data = json_decode($response, true);

  if ($data[0] === "SUCCESS") {
      $stdNameInUrdu = $data[1][0][1][0];
  } else {
      echo "Failed";
  }
}

function sqlDateToUrduRTL($sqlDate) {
    $months = [
        '01' => 'جنوری',
        '02' => 'فروری',
        '03' => 'مارچ',
        '04' => 'اپریل',
        '05' => 'مئی',
        '06' => 'جون',
        '07' => 'جولائی',
        '08' => 'اگست',
        '09' => 'ستمبر',
        '10' => 'اکتوبر',
        '11' => 'نومبر',
        '12' => 'دسمبر'
    ];

    $date = DateTime::createFromFormat('Y-m-d', $sqlDate);
    if (!$date) return '';

    // Convert digits to Urdu
    $en = ['0','1','2','3','4','5','6','7','8','9'];
    $ur = ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'];

    $day   = str_replace($en, $ur, $date->format('d'));
    $month = $months[$date->format('m')];
    $year  = str_replace($en, $ur, $date->format('Y'));

    return "$year $month $day";
}
?>
<!doctype html>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Certificate • <?= htmlspecialchars($row['title']) ?></title>
<style>
body {
  margin:0; padding:0;
  font-family: "Georgia", serif;
  background:#fff;
  /*  */
  min-height:100vh;
}
.certificate {
  border: 3px solid black;
  padding: 10px !important;
  width: 1052px;
  height: 768px;
  background: url('edited.png') no-repeat center center;
  background-size: cover;
  position: relative;
  text-align: center;
}
.certificate .name {
  position: absolute;
  top: 300px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 24px;
  font-weight: bold;
  color: #000;
  width: 80%;
}
.certificate .text {
  position: absolute;
  top: 345px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 18px;
  color: #000;
  width: 80%;
  line-height: 1.6;
}
.certificate .date {
  position: absolute;
  bottom: 100px;
  left: 100px;
  font-size: 16px;
  color:#000;
}
.certificate .director {
  position: absolute;
  bottom: 80px;
  right: 120px;
  font-size: 16px;
  font-weight: bold;
  color:#000;
}
</style>
</head>
<body>
  <div class="mt-2 mb-2 nonPrintable" align=center>
    <button onclick="generatePDF('<?php echo $title; ?>')" class="btn btn-primary btn-sm">Download as PDF</button>
    <!-- <button class="btn btn-primary btn-sm" id="printBtn" onclick="window.print()">Download PDF</button> -->
  </div>

  <div class="container-fluid printable" id="certificateContainer" style="display:flex; justify-content:center; align-items:center;">
    <?php
    if($certificateLang=='english'){
    ?>
      <div class="certificate" style="background-image: url('./images/cerEng.png');">

        <div class="name" style="margin-top: 10px"><span style="font-weight: 100 !important; font-size: 22px !important">This credential is awarded to</span><br>Mr./Ms. <?= htmlspecialchars($row['full_name']) ?></div>

        <div class="text" style="font-size: 22px">
          <br>Based on your answers to 50 questions,<br>
          you have scored <?= (int)$marksObtained ?>/<?= (int)$totalMarks ?>.<br><br>
          <!-- <br>Based on the <?= (int)$row['score'] ?> answers submitted by you,<br>
          it is certified that you bear <strong><?= $percent >= 50 ? "Good" : "Average" ?></strong> character.<br><br> -->
          <em>Hearty Congratulations.</em><br>
          <em>Date: <?= date("d M Y", strtotime($row['completed_at'])) ?></em>
        </div>

      </div>
    <?php
    }

    else{
    ?>
      <div class="certificate" style="background-image: url('./images/cerUrdu.jpg');">

        <div class="name" style="margin-top: 10px"><span style="font-weight: 100 !important; font-size: 22px !important">وثوق نامہ</span><br>محترم / محترمہ <?= htmlspecialchars($stdNameInUrdu) ?></div>

        <div class="text" style="font-size: 22px">
          <br>دیے گئے پچاس سوالات کے جوابات کی بنیاد پر,<br>
           آپ کو <?= $marksObtained ?>/<?= $totalMarks ?> نمبرات حاصل ہوئے ہیں<br><br>
          <!-- <br>Based on the <?= (int)$row['score'] ?> answers submitted by you,<br>
          it is certified that you bear <strong><?= $percent >= 50 ? "Good" : "Average" ?></strong> character.<br><br> -->-
          دلی مبارکباد<br>
          <span dir="rtl">
            <?=  sqlDateToUrduRTL($row['completed_date']) ?>
          </span>: تاریخ
          <br><br><br>
          ڈائریکٹر
        </div>

      </div>
    <?php
    }
    ?>
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.3/html2pdf.bundle.min.js"></script>
  <script type="text/javascript">
  function generatePDF(quiz_title) {
      const element = document.getElementById('certificateContainer'); // Target the specific HTML element
      html2pdf().from(element).set({
          margin: 0.2,
          filename: quiz_title+'_certificate.pdf',
          image: { type: 'jpeg', quality: 0.98 },
          html2canvas: { scale: 3 },
          jsPDF: {
              unit: 'in',
              format: 'letter',
              orientation: 'landscape'
          }
      }).save();
      // html2pdf().from(element).save('my-document.pdf');
  }
  </script>
</body>
</html>
