<?php
// profile.php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// دالة الحماية
if (!function_exists('esc')) {
    function esc($v) {
        return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// معالجة اللغة
$lang = $_GET['lang'] ?? ($_SESSION['lang'] ?? 'en');
$lang = in_array($lang, ['en','ar']) ? $lang : 'en';
$is_ar = $lang === 'ar';

// التحقق من معرف المستخدم
$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
    header('Location: login.php');
    exit;
}

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

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

$username    = $user['username'] ?? 'user';
$full_name   = $user['full_name'] ?? ($user['name'] ?? '');
$email       = $user['email'] ?? '';
$note        = $user['note'] ?? '';
$avatar_db   = $user['avatar'] ?? '';
$avatar_default = 'assets/img/avatar.png'; // تأكد من وجود صورة افتراضية في هذا المسار
$avatar_url = ($avatar_db && file_exists(__DIR__.'/'.$avatar_db)) ? $avatar_db : $avatar_default;

$messages = [];
$errors = [];

/* --------------------------------------------------------------
   HANDLE AJAX AVATAR UPLOAD
-------------------------------------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'ajax_avatar') {
    header('Content-Type: application/json');

    if (empty($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['ok'=>0, 'msg'=>$is_ar ? 'لم يتم اختيار ملف' : 'No file uploaded']);
        exit;
    }

    $f = $_FILES['avatar'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime  = finfo_file($finfo, $f['tmp_name']);
    finfo_close($finfo);

    $allowed = ['image/jpeg','image/png','image/webp'];
    if (!in_array($mime, $allowed)) {
        echo json_encode(['ok'=>0,'msg'=>$is_ar?'صيغة غير مدعومة':'Unsupported file']);
        exit;
    }
    if ($f['size'] > 2*1024*1024) {
        echo json_encode(['ok'=>0,'msg'=>$is_ar?'الصورة كبيرة جداً (الحد الأقصى 2 ميجا)':'Too large (Max 2MB)']);
        exit;
    }

    $ext = $mime === 'image/png' ? 'png' : ($mime === 'image/webp' ? 'webp' : 'jpg');
    $newName = "avatar_u{$user_id}_" . time() . ".$ext";
    $targetDir = __DIR__ . '/assets/img/';
    if (!is_dir($targetDir)) mkdir($targetDir, 0755, true);
    $targetPath = $targetDir . $newName;

    if (!move_uploaded_file($f['tmp_name'], $targetPath)) {
        echo json_encode(['ok'=>0,'msg'=>$is_ar?'فشل في رفع الملف':'Upload failed']);
        exit;
    }

    $relative = 'assets/img/' . $newName;

    try {
        $pdo->prepare("UPDATE users SET avatar = ? WHERE id = ?")->execute([$relative, $user_id]);
        $_SESSION['avatar'] = $relative;
        if ($avatar_db && file_exists(__DIR__.'/'.$avatar_db) && str_contains($avatar_db,'avatar_u')) {
            @unlink(__DIR__.'/'.$avatar_db);
        }
        echo json_encode(['ok'=>1, 'file'=>$relative]);
    } catch (Exception $e) {
        echo json_encode(['ok'=>0, 'msg'=>$e->getMessage()]);
    }
    exit;
}

/* --------------------------------------------------------------
   HANDLE PROFILE SAVE
-------------------------------------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_profile') {
    $new_fullname = trim($_POST['full_name'] ?? '');
    $new_email    = trim($_POST['email'] ?? '');
    $new_note      = trim($_POST['note'] ?? '');
    $new_pass      = trim($_POST['password'] ?? '');

    if ($new_fullname === '') {
        $errors[] = $is_ar ? 'الاسم الكامل مطلوب' : 'Full name is required';
    }

    if ($new_email !== '' && !filter_var($new_email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = $is_ar ? 'البريد الإلكتروني غير صحيح' : 'Invalid email address';
    }

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();
            // تحديث الاسم والبريد
            $updated = false;
            $cols = ["full_name", "name"]; // محاولة تحديث أي عمود متاح
            foreach($cols as $col){
                try {
                    $stmt = $pdo->prepare("UPDATE users SET $col = ?, email = ? WHERE id = ?");
                    $stmt->execute([$new_fullname, $new_email, $user_id]);
                    $updated = true; break;
                } catch(Exception $e){}
            }
            
            // تحديث الملاحظة
            try { $pdo->prepare("UPDATE users SET note = ? WHERE id = ?")->execute([$new_note, $user_id]); } catch(Exception $e){}

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

            $pdo->commit();
            $messages[] = $is_ar ? '✅ تم تحديث بيانات الملف الشخصي بنجاح' : '✅ Profile updated successfully';
            
            // تحديث البيانات المحلية
            $full_name = $new_fullname;
            $email     = $new_email;
            $note      = $new_note;
        } catch (Exception $ex) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $errors[] = $ex->getMessage();
        }
    }
}
?>
<!doctype html>
<html lang="<?= $is_ar?'ar':'en' ?>" dir="<?= $is_ar?'rtl':'ltr' ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title><?= $is_ar?'الملف الشخصي':'My Profile' ?> | <?= esc($full_name) ?></title>

    <!-- Bootstrap 5 & Fonts -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #4361ee 0%, #3a0ca3 100%);
            --bg-body: #f0f2f5;
            --primary-color: #4361ee;
        }

        body { 
            background: var(--bg-body); 
            font-family: <?= $is_ar ? "'Tajawal', sans-serif" : "'Inter', sans-serif" ?>;
            color: #334155;
            min-height: 100vh;
        }

        .header-profile {
            background: #fff;
            padding: 1.5rem 0;
            border-bottom: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }

        .profile-container {
            max-width: 1000px;
            margin: 0 auto;
        }

        /* Sidebar Side */
        .card-profile-sidebar {
            background: #fff;
            border: none;
            border-radius: 20px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.05);
            overflow: hidden;
            text-align: center;
            padding: 2.5rem 1.5rem;
            position: sticky;
            top: 20px;
        }

        .avatar-wrapper {
            position: relative;
            width: 150px;
            height: 150px;
            margin: 0 auto 1.5rem;
        }

        .avatar-img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
            border: 5px solid #fff;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            transition: transform 0.3s ease;
        }

        .btn-change-avatar {
            position: absolute;
            bottom: 5px;
            right: 5px;
            background: var(--primary-color);
            color: #fff;
            width: 38px;
            height: 38px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            border: 3px solid #fff;
            transition: all 0.2s;
        }

        .btn-change-avatar:hover {
            transform: scale(1.1);
            background: #3046c4;
        }

        /* Main Form Area */
        .card-main {
            background: #fff;
            border: none;
            border-radius: 20px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.05);
            padding: 2.5rem;
        }

        .section-title {
            font-weight: 700;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 10px;
            color: #1e293b;
        }

        .form-label {
            font-weight: 600;
            font-size: 0.9rem;
            color: #64748b;
            margin-bottom: 0.5rem;
        }

        .form-control {
            border-radius: 12px;
            padding: 0.75rem 1rem;
            border: 1px solid #e2e8f0;
            background-color: #f8fafc;
            transition: all 0.2s;
        }

        .form-control:focus {
            background-color: #fff;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 4px rgba(67, 97, 238, 0.1);
        }

        .form-control[readonly] {
            background-color: #f1f5f9;
            cursor: not-allowed;
        }

        .btn-save-profile {
            background: var(--primary-gradient);
            border: none;
            color: #fff;
            padding: 0.8rem 2rem;
            border-radius: 12px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-save-profile:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(67, 97, 238, 0.3);
            color: #fff;
        }

        .alert {
            border-radius: 15px;
            border: none;
            padding: 1rem 1.25rem;
        }

        /* Responsive */
        @media (max-width: 991px) {
            .card-profile-sidebar {
                margin-bottom: 1.5rem;
                position: static;
            }
        }
    </style>
</head>
<body class="<?= $is_ar ? 'rtl' : '' ?>">

<header class="header-profile">
    <div class="container profile-container">
        <div class="d-flex align-items-center justify-content-between">
            <div>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-1">
                        <li class="breadcrumb-item"><a href="index.php" class="text-decoration-none text-muted small"><?= $is_ar ? 'الرئيسية' : 'Dashboard' ?></a></li>
                        <li class="breadcrumb-item active small" aria-current="page"><?= $is_ar ? 'الملف الشخصي' : 'Profile' ?></li>
                    </ol>
                </nav>
                <h3 class="mb-0 fw-bold"><?= $is_ar ? 'إعدادات الحساب' : 'Account Settings' ?></h3>
            </div>
            <div class="d-flex gap-2">
                <a href="?lang=<?= $is_ar ? 'en' : 'ar' ?>" class="btn btn-light border btn-sm rounded-pill px-3">
                    <i class="fa fa-globe me-1"></i> <?= $is_ar ? 'English' : 'العربية' ?>
                </a>
            </div>
        </div>
    </div>
</header>

<div class="container profile-container mb-5">
    <div class="row">
        <!-- Sidebar -->
        <div class="col-lg-4">
            <div class="card-profile-sidebar shadow-sm">
                <div class="avatar-wrapper">
                    <img id="avatarPreview" src="<?= esc($avatar_url) ?>" class="avatar-img shadow" alt="Avatar">
                    <label class="btn-change-avatar" for="avatarInput" title="<?= $is_ar ? 'تغيير الصورة' : 'Change Avatar' ?>">
                        <i class="fa fa-camera"></i>
                    </label>
                    <input type="file" id="avatarInput" accept="image/*" hidden>
                </div>
                
                <h4 class="fw-bold mb-1"><?= esc($full_name ?: $username) ?></h4>
                <p class="text-muted small mb-4">@<?= esc($username) ?></p>
                
                <div class="d-grid gap-2 mt-2">
                    <a href="index.php" class="btn btn-outline-secondary btn-sm border-0 py-2 rounded-3">
                        <i class="fa-solid fa-house me-2 ms-2"></i> <?= $is_ar ? 'العودة للرئيسية' : 'Back to Home' ?>
                    </a>
                </div>
            </div>
        </div>

        <!-- Main Form -->
        <div class="col-lg-8">
            <div class="card-main">
                
                <?php if($errors): ?>
                    <div class="alert alert-danger shadow-sm mb-4">
                        <ul class="mb-0 list-unstyled">
                            <?php foreach($errors as $e): ?>
                                <li><i class="fa-solid fa-circle-exclamation me-2 ms-2"></i> <?= esc($e) ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <?php if($messages): ?>
                    <div class="alert alert-success shadow-sm mb-4">
                        <?php foreach($messages as $m): ?>
                            <div class="d-flex align-items-center"><i class="fa-solid fa-circle-check me-2 ms-2"></i> <?= esc($m) ?></div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <form method="post" id="profileForm">
                    <input type="hidden" name="action" value="save_profile">
                    
                    <h5 class="section-title">
                        <i class="fa-solid fa-user-gear text-primary"></i>
                        <?= $is_ar ? 'المعلومات الأساسية' : 'Basic Information' ?>
                    </h5>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?= $is_ar ? 'اسم المستخدم' : 'Username' ?></label>
                            <input class="form-control" value="<?= esc($username) ?>" readonly>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?= $is_ar ? 'الاسم الكامل' : 'Full Name' ?></label>
                            <input name="full_name" class="form-control" value="<?= esc($full_name) ?>" required>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label"><?= $is_ar ? 'البريد الإلكتروني' : 'Email Address' ?></label>
                        <input name="email" class="form-control" type="email" value="<?= esc($email) ?>">
                    </div>

                    <hr class="my-4 opacity-25">

                    <h5 class="section-title">
                        <i class="fa-solid fa-lock text-primary"></i>
                        <?= $is_ar ? 'الأمان' : 'Security' ?>
                    </h5>
                    
                    <div class="mb-4">
                        <label class="form-label"><?= $is_ar ? 'كلمة المرور الجديدة' : 'New Password' ?></label>
                        <input name="password" class="form-control" type="password" placeholder="<?= $is_ar ? 'اتركها فارغة إذا لم ترد التغيير' : 'Leave empty to keep current password' ?>">
                    </div>

                    <hr class="my-4 opacity-25">

                    <h5 class="section-title">
                        <i class="fa-solid fa-pen-nib text-primary"></i>
                        <?= $is_ar ? 'إضافات' : 'Extra' ?>
                    </h5>

                    <div class="mb-4">
                        <label class="form-label"><?= $is_ar ? 'ملاحظات' : 'Bio / Notes' ?></label>
                        <textarea name="note" class="form-control" rows="3"><?= esc($note) ?></textarea>
                    </div>

                    <div class="mt-5 d-flex justify-content-end">
                        <button class="btn btn-save-profile px-5" type="submit">
                            <i class="fa-solid fa-check-circle me-2 ms-2"></i>
                            <?= $is_ar ? 'حفظ التغييرات' : 'Save Changes' ?>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    // Avatar AJAX Preview & Upload
    const avatarInput = document.getElementById("avatarInput");
    const avatarPreview = document.getElementById("avatarPreview");

    avatarInput.addEventListener("change", async () => {
        const file = avatarInput.files[0];
        if (!file) return;

        // إظهار معاينة فورية قبل الرفع
        const originalSrc = avatarPreview.src;
        avatarPreview.src = URL.createObjectURL(file);

        const formData = new FormData();
        formData.append("action", "ajax_avatar");
        formData.append("avatar", file);

        try {
            const response = await fetch(window.location.href, { 
                method: "POST", 
                body: formData 
            });
            const result = await response.json();

            if (result.ok) {
                avatarPreview.src = result.file + "?t=" + Date.now();
                Swal.fire({
                    icon: 'success',
                    title: '<?= $is_ar ? "تم تحديث الصورة" : "Avatar Updated" ?>',
                    timer: 1500,
                    showConfirmButton: false,
                    toast: true,
                    position: 'top-end'
                });
            } else {
                avatarPreview.src = originalSrc;
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: result.msg
                });
            }
        } catch (error) {
            avatarPreview.src = originalSrc;
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Network error or server failed.'
            });
        }
    });
</script>

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