<?php
include "db.php";
session_start();

// Check if the user is logged in
if (!isset($_SESSION["user_id"])) {
    header("Location: index.php");
    exit();
}

// Create connection
try {
    $db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Check if certificate_id is provided
if (!isset($_GET['certificate_id'])) {
    header("Location: all-certificates.php");
    exit();
}

$certificate_id = $_GET['certificate_id'];

// Initialize variables
$student_id = "";
$student_name = "";
$course_name = "";
$date_of_joining = "";
$grade = "";
$error_message = "";
$success_message = "";

// Fetch existing certificate details
$query = "SELECT * FROM certificates WHERE certificate_id = :certificate_id";
$stmt = $db->prepare($query);
$stmt->bindParam(":certificate_id", $certificate_id);
$stmt->execute();
$certificate = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$certificate) {
    $error_message = "Certificate not found.";
} else {
    $student_id = $certificate['student_id'];
    $student_name = $certificate['student_name'];
    $course_name = $certificate['course_name'];
    $date_of_joining = $certificate['date_of_joining'];
    $grade = $certificate['grade'];
}

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["update_certificate"])) {
    $new_course_name = $_POST["course_name"];
    $new_date_of_joining = $_POST["date_of_joining"];
    $new_certificate_id = trim($_POST["certificate_id"]);
    $new_grade = trim($_POST["grade"]);

    // Validate certificate ID uniqueness if changed
    if ($new_certificate_id !== $certificate_id) {
        $checkQuery = "SELECT * FROM certificates WHERE certificate_id = :new_certificate_id";
        $checkStmt = $db->prepare($checkQuery);
        $checkStmt->bindParam(":new_certificate_id", $new_certificate_id);
        $checkStmt->execute();
        if ($checkStmt->fetch(PDO::FETCH_ASSOC)) {
            $error_message = "Certificate ID already exists. Please choose a different ID.";
        }
    }

    if (empty($error_message)) {
        // Update the certificate details
        $updateQuery = "UPDATE certificates SET course_name = :course_name, date_of_joining = :date_of_joining, certificate_id = :new_certificate_id, grade = :grade WHERE certificate_id = :certificate_id";
        $updateStmt = $db->prepare($updateQuery);
        $updateStmt->bindParam(":course_name", $new_course_name);
        $updateStmt->bindParam(":date_of_joining", $new_date_of_joining);
        $updateStmt->bindParam(":new_certificate_id", $new_certificate_id);
        $updateStmt->bindParam(":grade", $new_grade);
        $updateStmt->bindParam(":certificate_id", $certificate_id);

        try {
            $updateStmt->execute();
            $success_message = "Certificate updated successfully.";
            // Redirect to all-certificates.php after 2 seconds
            echo '<script>
                setTimeout(function() {
                    window.location.href = "all-certificates.php";
                }, 2000);
            </script>';
        } catch (Exception $e) {
            $error_message = "Error updating certificate: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Certificate</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <?php include "nav.php"; ?>
    <div class="container mt-5">
        <h2>Edit Certificate</h2>
        <?php if (!empty($success_message)): ?>
            <div class="alert alert-success" role="alert">
                <?php echo $success_message; ?>
            </div>
        <?php endif; ?>
        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger" role="alert">
                <?php echo $error_message; ?>
            </div>
        <?php endif; ?>

        <?php if ($certificate): ?>
            <form method="POST">
                <div class="form-group">
                    <label>Student ID</label>
                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($student_id); ?>" readonly>
                </div>
                <div class="form-group">
                    <label>Student Name</label>
                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($student_name); ?>" readonly>
                </div>
                <div class="form-group">
                    <label>Course Name</label>
                    <input type="text" name="course_name" class="form-control" value="<?php echo htmlspecialchars($course_name); ?>" required>
                </div>
                <div class="form-group">
                    <label>Date of Joining</label>
                    <input type="date" name="date_of_joining" class="form-control" value="<?php echo htmlspecialchars($date_of_joining); ?>" required>
                </div>
            <div class="form-group">
                <label>Certificate ID</label>
                <input type="text" name="certificate_id" class="form-control" value="<?php echo htmlspecialchars($certificate_id); ?>" required>
            </div>
            <div class="form-group">
                <label>Grade</label>
                <input type="text" name="grade" class="form-control" value="<?php echo htmlspecialchars($grade); ?>" placeholder="Enter Grade (optional)">
            </div>
            <button type="submit" name="update_certificate" class="btn btn-primary">Update Certificate</button>
            <a href="all-certificates.php" class="btn btn-secondary ml-2">Cancel</a>
        </form>
    <?php endif; ?>
</div>
    <!-- Bootstrap JS -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
