<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../src/auth.php';

/* ===== صلاحية عرض الملف ===== */
authorize($pdo, 'profile', 'can_view');

$user_id = (int)$_SESSION['user_id'];
$message = '';
$error   = '';

/* ===== جلب بيانات المستخدم ===== */
$stmt = $pdo->prepare("
    SELECT user_id, username, full_name
    FROM users
    WHERE user_id = ?
    LIMIT 1
");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if (!$user) {
    die('User not found');
}

/* ===== حماية من NULL (PHP 8.1+) ===== */
$user['username']  = $user['username']  ?? '';
$user['full_name'] = $user['full_name'] ?? '';

/* ===== تحديث البيانات ===== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    authorize($pdo, 'profile', 'can_edit');

    $full_name = trim($_POST['full_name'] ?? '');
    $password  = $_POST['password'] ?? '';
    $confirm   = $_POST['confirm_password'] ?? '';

    if ($full_name === '') {
        $error = 'Full name is required';
    } elseif ($password !== '' && $password !== $confirm) {
        $error = 'Password confirmation does not match';
    } else {
        try {

            if ($password !== '') {
                // تحديث الاسم + كلمة المرور
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $upd = $pdo->prepare("
                    UPDATE users
                    SET full_name = ?, password = ?
                    WHERE user_id = ?
                ");
                $upd->execute([$full_name, $hash, $user_id]);
            } else {
                // تحديث الاسم فقط
                $upd = $pdo->prepare("
                    UPDATE users
                    SET full_name = ?
                    WHERE user_id = ?
                ");
                $upd->execute([$full_name, $user_id]);
            }

            $message = 'Profile updated successfully';

            // إعادة تحميل البيانات
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();

            // حماية بعد التحديث
            $user['username']  = $user['username']  ?? '';
            $user['full_name'] = $user['full_name'] ?? '';

        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Profile</title>
<link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
<style>
:root{
    --bg:#f1f5f9;
    --card:#ffffff;
    --border:#e5e7eb;
    --text:#1f2937;
    --muted:#6b7280;
    --primary:#2563eb;
    --success:#16a34a;
    --danger:#dc2626;
    --shadow:0 10px 25px rgba(0,0,0,.06);
}
body{
    margin:0;
    background:var(--bg);
    font-family:'Inter','Segoe UI',Arial,sans-serif;
    color:var(--text);
}
.container{
    max-width:520px;
    margin:50px auto;
}
.card{
    background:var(--card);
    border-radius:14px;
    border:1px solid var(--border);
    box-shadow:var(--shadow);
    overflow:hidden;
}
.card-header{
    padding:20px;
    border-bottom:1px solid var(--border);
    font-weight:800;
    font-size:1rem;
}
.card-body{
    padding:25px;
}
label{
    font-size:12px;
    font-weight:700;
    color:var(--muted);
    display:block;
    margin-bottom:6px;
}
input{
    width:100%;
    padding:11px 12px;
    border-radius:10px;
    border:1px solid var(--border);
    font-size:14px;
    margin-bottom:16px;
}
input[readonly]{
    background:#f8fafc;
}
.alert-success{
    background:#dcfce7;
    color:#166534;
    padding:10px 14px;
    border-radius:10px;
    margin-bottom:15px;
    font-size:13px;
}
.alert-error{
    background:#fee2e2;
    color:#991b1b;
    padding:10px 14px;
    border-radius:10px;
    margin-bottom:15px;
    font-size:13px;
}
.actions{
    display:flex;
    justify-content:space-between;
    align-items:center;
    margin-top:20px;
}
.btn{
    padding:10px 18px;
    border-radius:10px;
    font-size:13px;
    font-weight:800;
    border:none;
    cursor:pointer;
    display:inline-flex;
    align-items:center;
    gap:6px;
}
.btn-save{background:var(--primary);color:#fff}
.btn-back{background:#334155;color:#fff;text-decoration:none}
</style>
</head>
<body>
 <a href="dashboard.php" class="btn btn-gray">
                <i class="fas fa-arrow-left"></i> Back
            </a>
<div class="container">

<div class="card">
    <div class="card-header">
        <i class="fas fa-user"></i> My Profile
    </div>

    <div class="card-body">

        <?php if ($message): ?>
            <div class="alert-success"><?= htmlspecialchars($message) ?></div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert-error"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <form method="post">

            <label>Username</label>
            <input type="text"
                   value="<?= htmlspecialchars($user['username']) ?>"
                   readonly>

            <label>Full Name</label>
            <input type="text"
                   name="full_name"
                   value="<?= htmlspecialchars($user['full_name']) ?>"
                   required>

            <hr style="border:none;border-top:1px dashed #e5e7eb;margin:20px 0">

            <label>New Password (optional)</label>
            <input type="password"
                   name="password"
                   placeholder="Leave blank to keep current password">

            <label>Confirm Password</label>
            <input type="password"
                   name="confirm_password">

            <div class="actions">
                <a href="dashboard.php" class="btn btn-back">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <button type="submit" class="btn btn-save">
                    <i class="fas fa-save"></i> Save Changes
                </button>
            </div>

        </form>

    </div>
</div>

</div>

</body>
</html>
