<?php

require_once '../includes/auth.php';

require_login();

$user = current_user();

$userId = $user['id'] ?? null;


if (!$userId) {

    header("Location: ../auth/login.php");
    exit;

}


if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

    header("Location: ../dashboard/my-profile.php");
    exit;

}


$institution =
    trim($_POST['institution'] ?? '');

$courseOfStudy =
    trim($_POST['course_of_study'] ?? '');

$qualification =
    trim($_POST['qualification'] ?? '');

$graduationYear =
    trim($_POST['graduation_year'] ?? '');


/*
|--------------------------------------------------------------------------
| VALIDATE GRADUATION YEAR
|--------------------------------------------------------------------------
*/

if ($graduationYear !== '') {

    $currentYear = (int) date('Y');

    if (
        !ctype_digit($graduationYear) ||
        (int) $graduationYear < 1950 ||
        (int) $graduationYear > $currentYear
    ) {

        $_SESSION['error'] =
            'Please enter a valid graduation year.';

        header("Location: ../dashboard/my-profile.php");
        exit;

    }

}


try {


    $stmt = $db->prepare("
        UPDATE corps_members

        SET
            institution = ?,
            course_of_study = ?,
            qualification = ?,
            graduation_year = ?

        WHERE user_id = ?
    ");


    $stmt->execute([

        $institution !== ''
            ? $institution
            : null,

        $courseOfStudy !== ''
            ? $courseOfStudy
            : null,

        $qualification !== ''
            ? $qualification
            : null,

        $graduationYear !== ''
            ? $graduationYear
            : null,

        $userId

    ]);


    $_SESSION['success'] =
        'Academic information updated successfully.';


} catch (PDOException $e) {


    $_SESSION['error'] =
        'Unable to update academic information.';


}


header("Location: ../dashboard/my-profile.php");
exit;