<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Student Profile
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/student-auth.php';

$pdo = db();

requireStudent();

if (isPost()) { requireCsrf(); }

$student = currentStudent($pdo);

if (!$student) {

    studentLogout();

    redirectTo('login.php');
}

$success = '';
$error = '';

/*
|--------------------------------------------------------------------------
| Update Profile
|--------------------------------------------------------------------------
*/

if (isPost()) {

    $fullName =
        trim($_POST['full_name'] ?? '');

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

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

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

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

    if (
        $fullName === ''
        ||
        $phone === ''
        ||
        !in_array($gender, ['male','female'], true)
        ||
        ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL))
    ) {

        $error =
            'Please complete required fields.';
    }

    else {

        try {

            $profileImage =
                $student['profile_image']
                ?? '';

            /*
            |--------------------------------------------------------------------------
            | Upload Image
            |--------------------------------------------------------------------------
            */

            if (
                !empty(
                    $_FILES['profile_image']['name']
                )
            ) {

                $uploaded =
                    secureUpload(

                        $_FILES['profile_image'],

                        'profile-images',

                        [
                            'jpg',
                            'jpeg',
                            'png',
                            'webp'
                        ]

                    );

                if (!$uploaded) {
                    throw new RuntimeException('The profile image must be JPG, PNG or WebP and within the allowed size.');
                }

                $profileImage = $uploaded;
            }

            /*
            |--------------------------------------------------------------------------
            | Update Student
            |--------------------------------------------------------------------------
            */

            $stmt = $pdo->prepare("

                UPDATE students

                SET

                    full_name = ?,
                    email = ?,
                    phone = ?,
                    whatsapp = ?,
                    whatsapp_number = ?,
                    country = ?,
                    nationality = ?,
                    gender = ?,
                    profile_image = ?,
                    updated_at = ?

                WHERE id = ?

            ");

            $stmt->execute([

                $fullName,
                $email !== '' ? $email : null,
                $phone,
                $phone,
                $phone,
                $country !== '' ? $country : null,
                $country !== '' ? $country : null,
                $gender,
                $profileImage,
                now(),
                $student['id']

            ]);

            logActivity(

                $pdo,

                'student',

                (int)$student['id'],

                'Profile Updated',

                'Student updated profile.'

            );

            $success =
                'Profile updated successfully.';

            $student =
                currentStudent($pdo);

        } catch(Throwable $e) {

            error_log('[SMI profile] ' . $e->getMessage());
            $error = APP_DEBUG ? $e->getMessage() : 'Failed to update profile.';
        }
    }
}

?>

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta
name="viewport"
content="width=device-width, initial-scale=1.0">

<title>
Student Profile
</title>

<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap"
rel="stylesheet">

<link
rel="stylesheet"
href="../assets/css/style.css">

<style>

.profile-hero{

    background:
    linear-gradient(
        135deg,
        #0f172a,
        #1e293b
    );

    color:#fff;

    border-radius:40px;

    padding:45px;

    margin-bottom:30px;

    position:relative;

    overflow:hidden;
}

.profile-hero::before{

    content:'';

    position:absolute;

    width:300px;
    height:300px;

    border-radius:50%;

    background:
        rgba(255,255,255,0.05);

    top:-120px;
    right:-100px;
}

.profile-hero h1{

    font-size:50px;

    font-weight:900;

    margin-bottom:14px;

    position:relative;
}

.profile-hero p{

    color:#cbd5e1;

    line-height:2;

    position:relative;
}

.profile-layout{

    display:grid;

    grid-template-columns:340px 1fr;

    gap:28px;
}

.profile-card{

    background:#fff;

    border-radius:34px;

    padding:32px;

    border:1px solid #e2e8f0;

    box-shadow:
        0 18px 40px rgba(15,23,42,0.05);
}

.avatar-box{

    text-align:center;
}

.avatar{

    width:170px;
    height:170px;

    border-radius:40px;

    margin:auto;

    overflow:hidden;

    background:
    linear-gradient(
        135deg,
        #2563eb,
        #7c3aed
    );

    display:flex;

    align-items:center;

    justify-content:center;

    color:#fff;

    font-size:60px;

    font-weight:900;

    margin-bottom:24px;
}

.avatar img{

    width:100%;
    height:100%;

    object-fit:cover;
}

.student-name{

    font-size:30px;

    font-weight:900;

    margin-bottom:10px;
}

.student-code{

    color:#64748b;

    font-size:15px;

    line-height:1.8;
}

.info-grid{

    display:grid;

    grid-template-columns:1fr 1fr;

    gap:20px;
}

.info-box{

    background:#f8fafc;

    border-radius:24px;

    padding:20px;

    border:1px solid #e2e8f0;
}

.info-box h4{

    color:#64748b;

    margin-bottom:10px;

    font-size:14px;
}

.info-box p{

    font-size:18px;

    font-weight:800;
}

.save-btn{

    width:100%;

    border:none;

    background:
    linear-gradient(
        135deg,
        #2563eb,
        #1d4ed8
    );

    color:#fff;

    padding:18px;

    border-radius:22px;

    font-size:16px;

    font-weight:900;

    cursor:pointer;
}

.back-btn{

    display:inline-flex;

    align-items:center;

    justify-content:center;

    padding:14px 22px;

    border-radius:18px;

    background:#eff6ff;

    color:#2563eb;

    font-weight:900;
}

@media(max-width:1000px){

    .profile-layout{

        grid-template-columns:1fr;
    }
}

@media(max-width:700px){

    .profile-hero{

        padding:30px 24px;
    }

    .profile-hero h1{

        font-size:38px;
    }

    .info-grid{

        grid-template-columns:1fr;
    }
}

</style>

</head>

<body>

<div class="container page-padding">

    <div class="topbar">

        <h1 class="page-title">
            Student Profile
        </h1>

        <a
        href="dashboard.php"
        class="back-btn">

            ← Dashboard

        </a>

    </div>

    <div class="profile-hero">

        <h1>
            Academic Identity
        </h1>

        <p>

            Manage your academic information,
            personal profile, and official student data.

        </p>

    </div>

    <?php if($error): ?>

        <div class="alert alert-danger">

            <?php echo e($error); ?>

        </div>

    <?php endif; ?>

    <?php if($success): ?>

        <div class="alert alert-success">

            <?php echo e($success); ?>

        </div>

    <?php endif; ?>

    <div class="profile-layout">

        <div class="profile-card">

            <div class="avatar-box">

                <div class="avatar">

                    <?php if(!empty($student['profile_image'])): ?>

                        <img
                        src="../<?php echo e(ltrim((string)$student['profile_image'], '/')); ?>"
                        alt="Profile">

                    <?php else: ?>

                        <?php
                        echo strtoupper(
                            substr(
                                $student['full_name'],
                                0,
                                1
                            )
                        );
                        ?>

                    <?php endif; ?>

                </div>

                <div class="student-name">

                    <?php echo e($student['full_name']); ?>

                </div>

                <div class="student-code">

                    <?php echo e($student['student_code']); ?>

                    <br>

                  <?php
echo e(
    $student['student_card']
    ??
    $student['student_card_number']
    ??
    'No Card'
);
?>
                </div>

            </div>

        </div>

        <div class="profile-card">

            <form
            method="POST"
            enctype="multipart/form-data">
<?php echo csrfField(); ?>

                <div class="info-grid">

                    <div class="form-group">

                        <label>
                            Full Name
                        </label>

                        <input
                        type="text"
                        name="full_name"
                        class="form-control"
                        value="<?php echo e($student['full_name']); ?>"
                        required>

                    </div>

                    <div class="form-group">

                        <label>
                            Email
                        </label>

                        <input
                        type="email"
                        name="email"
                        class="form-control"
                        value="<?php echo e($student['email'] ?? ''); ?>"
                        required>

                    </div>

                    <div class="form-group">

                        <label>
                            Phone
                        </label>

                        <input
                        type="text"
                        name="phone"
                        class="form-control"
                        value="<?php echo e($student['phone'] ?? ''); ?>">

                    </div>

                    <div class="form-group">

                        <label>
                            Country
                        </label>

                        <input
                        type="text"
                        name="country"
                        class="form-control"
                        value="<?php echo e($student['country'] ?? ''); ?>">

                    </div>

                    <div class="form-group">

                        <label>
                            Gender
                        </label>

                        <select
                        name="gender"
                        class="form-control">

                            <option value="">
                                Select Gender
                            </option>

                            <option
                            value="male"
                            <?php echo ($student['gender'] ?? '') === 'male' ? 'selected' : ''; ?>>

                                Male

                            </option>

                            <option
                            value="female"
                            <?php echo ($student['gender'] ?? '') === 'female' ? 'selected' : ''; ?>>

                                Female

                            </option>

                        </select>

                    </div>

                    <div class="form-group">

                        <label>
                            Profile Image
                        </label>

                        <input
                        type="file"
                        name="profile_image"
                        class="form-control">

                    </div>

                </div>

                <button
                type="submit"
                class="save-btn">

                    Save Profile

                </button>

            </form>

        </div>

    </div>

</div>

<script src="../assets/js/app.js"></script>

</body>
</html>