<?php
declare(strict_types=1);

require_once '../includes/auth.php';
require_once '../includes/security.php';
require_once '../includes/csrf.php';
require_once '../config/database.php';

verify_csrf();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../admin/universities.php');
    exit;
}

$action = $_POST['action'] ?? '';

switch ($action) {

    case 'add':

        $name = trim($_POST['university_name'] ?? '');
        $video = trim($_POST['video_url'] ?? '');

        if ($name === '') {
            $_SESSION['error'] = 'University name is required.';
            break;
        }

        $check = $pdo->prepare("SELECT id FROM universities WHERE university_name = ? LIMIT 1");
        $check->execute([$name]);

        if ($check->fetch()) {
            $_SESSION['error'] = 'University already exists.';
            break;
        }

        $insert = $pdo->prepare("
            INSERT INTO universities
            (university_name, video_url)
            VALUES (?, ?)
        ");

        $insert->execute([
            $name,
            $video
        ]);

        $_SESSION['success'] = 'University added successfully.';
        break;



    case 'edit':

        $id = (int)($_POST['id'] ?? 0);
        $name = trim($_POST['university_name'] ?? '');
        $video = trim($_POST['video_url'] ?? '');

        if ($id <= 0 || $name === '') {
            $_SESSION['error'] = 'Invalid request.';
            break;
        }

        $update = $pdo->prepare("
            UPDATE universities
            SET
                university_name = ?,
                video_url = ?
            WHERE id = ?
        ");

        $update->execute([
            $name,
            $video,
            $id
        ]);

        $_SESSION['success'] = 'University updated successfully.';
        break;



    case 'delete':

        $id = (int)($_POST['id'] ?? 0);

        if ($id <= 0) {
            $_SESSION['error'] = 'Invalid request.';
            break;
        }

        $delete = $pdo->prepare("
            DELETE FROM universities
            WHERE id = ?
        ");

        $delete->execute([$id]);

        $_SESSION['success'] = 'University deleted successfully.';
        break;



    default:

        $_SESSION['error'] = 'Invalid action.';
}

header('Location: ../admin/universities.php');
exit;