<?php
session_start();
require 'config.php'; // unga DB connection

// 🔒 Eligibility check
if (
  !isset($_SESSION['user_id']) ||
  !isset($_SESSION['final_result']) ||
  $_SESSION['final_result'] !== 'PASS'
) {
  die("Not eligible for certificate");
}

$user_id = $_SESSION['user_id'];
$student_name = $_SESSION['username'];
$language = "Python";
$track = "Python Fundamentals";
$issue_date = date("Y-m-d");

// 🔁 Check if certificate already exists
$check = $conn->prepare("SELECT certificate_id FROM certificates WHERE user_id = ?");
$check->bind_param("i", $user_id);
$check->execute();
$res = $check->get_result();

if ($res->num_rows > 0) {
  $row = $res->fetch_assoc();
  $_SESSION['certificate_id'] = $row['certificate_id'];
  header("Location: generate_certificate_pdf.php");
  exit;
}

// 🆔 Generate Certificate ID
$year = date("Y");
$certificate_id = "RSL-PY-$year-" . str_pad(rand(1,999999), 6, "0", STR_PAD_LEFT);

// 💾 Insert record
$stmt = $conn->prepare("
  INSERT INTO certificates
  (certificate_id, user_id, student_name, language, track_name, issue_date)
  VALUES (?, ?, ?, ?, ?, ?)
");

$stmt->bind_param(
  "sissss",
  $certificate_id,
  $user_id,
  $student_name,
  $language,
  $track,
  $issue_date
);

$stmt->execute();

// Store for PDF
$_SESSION['certificate_id'] = $certificate_id;

// ➡️ Generate PDF
header("Location: generate_certificate_pdf.php");
exit;
