<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit;
}

require_once '../src/config/db.php';
require_once '../src/includes/functions.php';
require_once 'includes/lang.php';

// Handle Add/Edit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? null;
    $title = $_POST['title'];
    $description = $_POST['description'];
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $current_image = $_POST['current_image'] ?? '';

    $image_url = $current_image;
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = '../public/assets/img/certifications/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        $filename = uniqid() . '-' . basename($_FILES['image']['name']);
        $uploadFile = $uploadDir . $filename;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadFile)) {
            $image_url = 'assets/img/certifications/' . $filename;
            // Delete old image if a new one is uploaded and an old one exists
            if (!empty($current_image) && file_exists('../public/' . $current_image)) {
                unlink('../public/' . $current_image);
            }
        }
    }

    if ($id) { // Update
        $stmt = $pdo->prepare("UPDATE certifications SET title = ?, description = ?, image_url = ?, sort_order = ? WHERE id = ?");
        $stmt->execute([$title, $description, $image_url, $sort_order, $id]);
        header('Location: certifications.php?success=edit');
    } else { // Insert
        $stmt = $pdo->prepare("INSERT INTO certifications (title, description, image_url, sort_order) VALUES (?, ?, ?, ?)");
        $stmt->execute([$title, $description, $image_url, $sort_order]);
        header('Location: certifications.php?success=add');
    }

    exit;
}

// Fetch data for display
$edit_cert = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM certifications WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $edit_cert = $stmt->fetch();
}

// Ensure the table schema is correct before querying
ensure_certifications_table($pdo);
$unreadMessagesCount = $pdo->query("SELECT COUNT(*) FROM contact_messages WHERE is_read = 0")->fetchColumn();

$stmt = $pdo->query("SELECT * FROM certifications ORDER BY sort_order ASC, id DESC");
$certifications = $stmt->fetchAll();

$pageTitle = $t['certs_title'];
?>
<!DOCTYPE html>
<html lang="<?php echo $t['lang']; ?>" dir="<?php echo $t['dir']; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - VAULTIXAI</title>
    <link rel="stylesheet" href="<?php echo $bootstrapCSS; ?>" crossorigin="anonymous">
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <?php
    $currentPage = 'certifications';
    include 'includes/sidebar.php';
    ?>

    <div class="main-content">
        <div class="topbar">
            <h1><?php echo $edit_cert ? '✏️ ' : '🏆 '; echo $pageTitle; ?></h1>
            <?php if (!$edit_cert): ?>
                <a href="certifications.php#add-form" class="btn btn-add px-4 py-2">➕ <?php echo $t['certs_add_btn']; ?></a>
            <?php endif; ?>
        </div>

        <?php if (isset($_GET['success'])): ?>
            <div class="alert alert-success fw-bold mb-4">✅ <?php switch ($_GET['success']) {
                case 'add': echo $t['success_cert_added']; break;
                case 'edit': echo $t['success_cert_updated']; break;
                case 'delete': echo $t['success_cert_deleted']; break;
            } ?></div>
        <?php endif; ?>

        <div id="add-form" class="table-card p-4 p-md-5 mb-5">
            <?php include 'certification_form.php'; ?>
        </div>

        <div class="table-card">
            <div class="table-responsive">
                <?php include 'certification_list.php'; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
    <script src="assets/js/main.js"></script>
</body>
</html>