
<!-- Retrieve user information from the database -->
<?php include "db.php"; ?>

<?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());
}

// Initialize variable for generated message
$generated_message = null;
$error_message = null;

// Handle form submission for generating message
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["generate_message"])) {
    $input_certificate_id = trim($_POST["input_certificate_id"]);
    if (!empty($input_certificate_id)) {
        // Fetch certificate details by certificate_id
        $certQuery = "SELECT * FROM certificates WHERE certificate_id = :certificate_id";
        $certStmt = $db->prepare($certQuery);
        $certStmt->bindParam(":certificate_id", $input_certificate_id);
        $certStmt->execute();
        $certificate = $certStmt->fetch(PDO::FETCH_ASSOC);

            if ($certificate) {
                // Fetch student name
                $studentName = $certificate["student_name"];
                $certificateId = $certificate["certificate_id"];

                // Generate the Hindi and English messages as separate entries
                $generated_message = [
                    'hindi' => "प्रिय $studentName,\nआपने YPDO से अपना कोर्स पूरा कर लिया है। आपका सर्टिफिकेट आईडी $certificateId है। आप अपना सर्टिफिकेट ऑनलाइन https://youthpdorg.in/certificate-verify पर देख सकते हैं।\n\nसर्टिफिकेट डाउनलोड करने के लिए https://youthpdorg.in/generate-certificate पर जाएँ।",
                    'english' => "Dear $studentName,\nYou have completed your course from YPDO. Your certificate id is $certificateId. You Can Check your Certificate online https://youthpdorg.in/certificate-verify.\n\nfor Download Certificate https://youthpdorg.in/generate-certificate\n\nRegards \nYPDO"
                ];
            } else {
                $error_message = "Certificate ID not found.";
            }
    } else {
        $error_message = "Please enter a Certificate ID.";
    }
}

// Retrieve all issued certificates with isCertIssued flag from students table
$query = "SELECT c.*, s.isCertIssued FROM certificates c JOIN students s ON c.student_id = s.student_id";
$stmt = $db->query($query);
$certificates = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html>
<head>
    <title>All Certificates</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>All Certificates</h2>

        <!-- New form for generating text message -->
        <div class="card mb-4">
            <div class="card-header">
                Generate Text Message by Certificate ID
            </div>
            <div class="card-body">
                <form method="POST" class="form-inline">
                    <div class="form-group mr-2">
                        <input type="text" name="input_certificate_id" placeholder="Enter Certificate ID" class="form-control" required />
                    </div>
                    <button type="submit" name="generate_message" class="btn btn-info">Generate Message</button>
                </form>
                <?php if ($generated_message): ?>
                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label for="generatedMessageHindi">Generated Message (Hindi):</label>
                            <textarea id="generatedMessageHindi" class="form-control" rows="6" readonly><?php echo htmlspecialchars($generated_message['hindi']); ?></textarea>
                            <button class="btn btn-secondary mt-2" onclick="copyMessage('generatedMessageHindi')">Copy Hindi Message</button>
                        </div>
                        <div class="col-md-6">
                            <label for="generatedMessageEnglish">Generated Message (English):</label>
                            <textarea id="generatedMessageEnglish" class="form-control" rows="6" readonly><?php echo htmlspecialchars($generated_message['english']); ?></textarea>
                            <button class="btn btn-secondary mt-2" onclick="copyMessage('generatedMessageEnglish')">Copy English Message</button>
                        </div>
                    </div>
                <?php elseif ($error_message): ?>
                    <div class="alert alert-danger mt-3" role="alert">
                        <?php echo $error_message; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <?php if (count($certificates) > 0): ?>
            <table class="table">
                <thead>
                    <tr>
                        <th>Student ID</th>
                        <th>Student Name</th>
                        <th>Course Name</th>
                        <th>Certificate ID</th>
                        <th>Date of Joining</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($certificates as $certificate): ?>
                        <tr>
                            <td><?php echo $certificate["student_id"]; ?></td>
                            <td><?php echo $certificate["student_name"]; ?></td>
                            <td><?php echo $certificate["course_name"]; ?></td>
                            <td><?php echo $certificate["certificate_id"]; ?></td>
                            <td><?php echo $certificate["date_of_joining"]; ?></td>
                            <td>
                                <a href="delete-certificate.php?certificate_id=<?php echo $certificate['certificate_id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this certificate?')" <?php echo ($certificate['isCertIssued'] == 0) ? 'disabled' : ''; ?>>Delete</a>
                                <a href="edit-certificate.php?certificate_id=<?php echo $certificate['certificate_id']; ?>" class="btn btn-primary btn-sm ml-2" <?php echo ($certificate['isCertIssued'] == 0) ? 'disabled' : ''; ?>>Edit</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p>No certificates issued yet.</p>
        <?php endif; ?>
    </div>

    <!-- jQuery, Popper.js, and Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

    <script>
        function copyMessage(elementId) {
            var copyText = document.getElementById(elementId);
            copyText.select();
            copyText.setSelectionRange(0, 99999); // For mobile devices
            document.execCommand("copy");
            alert("Message copied to clipboard");
        }
    </script>
</body>
</html>
