<?php
// my_account.php
require_once 'config.php';

// บังคับให้เข้าสู่ระบบก่อนเข้าใช้งานหน้านี้
if (!isset($_SESSION['is_logged_in']) || $_SESSION['is_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$userId = $_SESSION['user_id'];
$alertMessage = "";
$alertType = "success";

// ข้อความแปลภาษาสำหรับหน้าบัญชีของฉัน
$account_translations = [
    'th' => [
        'title' => '👤 บัญชีของฉัน',
        'desc' => 'จัดการข้อมูลส่วนตัว ความปลอดภัย และตรวจสอบบทบาทของคุณในระบบ',
        'lbl_name' => 'ชื่อ-นามสกุล',
        'lbl_email' => 'อีเมลติดต่อ',
        'lbl_role' => 'ระดับผู้ใช้งาน (บทบาท)',
        'lbl_new_password' => 'รหัสผ่านใหม่ (ปล่อยว่างหากไม่ต้องการเปลี่ยน)',
        'ph_new_password' => 'ความยาวอย่างน้อย 6 ตัวอักษร...',
        'btn_save' => 'บันทึกข้อมูลส่วนตัว',
        'lbl_role_buyer' => 'ผู้ซื้อสินค้า (Buyer)',
        'lbl_role_seller' => 'ผู้ขายสินค้า (Seller)',
        'lbl_role_admin' => 'ผู้ดูแลระบบ (Admin)',
        'back_to_shop' => '← กลับหน้าร้านค้าหลัก',
        'success_update' => 'อัปเดตข้อมูลบัญชีผู้ใช้สำเร็จ!',
        'err_email_exist' => 'อีเมลนี้ถูกใช้งานโดยบัญชีอื่นแล้ว',
        'err_fields' => 'กรุณากรอกข้อมูลชื่อและอีเมลให้ถูกต้อง',
        'err_password_len' => 'รหัสผ่านใหม่ต้องยาวอย่างน้อย 6 ตัวอักษร',
        'err_db' => 'เกิดข้อผิดพลาดในการบันทึกข้อมูล: '
    ],
    'en' => [
        'title' => '👤 My Profile',
        'desc' => 'Manage your personal details, credentials, and check your system authorization status.',
        'lbl_name' => 'Full Name',
        'lbl_email' => 'Email Address',
        'lbl_role' => 'System Authorization (Role)',
        'lbl_new_password' => 'New Password (Leave blank to keep current)',
        'ph_new_password' => 'At least 6 characters...',
        'btn_save' => 'Save Changes',
        'lbl_role_buyer' => 'Buyer',
        'lbl_role_seller' => 'Seller',
        'lbl_role_admin' => 'Administrator',
        'back_to_shop' => '← Back to store',
        'success_update' => 'Profile updated successfully!',
        'err_email_exist' => 'This email is already associated with another account.',
        'err_fields' => 'Please provide a valid name and email address.',
        'err_password_len' => 'New password must be at least 6 characters long.',
        'err_db' => 'Database error occurred: '
    ]
];
$at = $account_translations[$lang];

// ดึงข้อมูลล่าสุดจากฐานข้อมูลเพื่อความสดใหม่
try {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();
    
    if (!$user) {
        // หากไม่พบผู้ใช้งานในระบบให้ล้างเซสชันแล้วส่งไปล็อกอินใหม่
        session_destroy();
        header('Location: login.php');
        exit;
    }
} catch (PDOException $e) {
    die("เชื่อมต่อฐานข้อมูลล้มเหลว: " . $e->getMessage());
}

// จัดการเมื่อมีการโพสต์ส่งข้อมูลฟอร์ม
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $newPass = $_POST['new_password'] ?? '';

    if (empty($name) || empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $alertMessage = $at['err_fields'];
        $alertType = "error";
    } else {
        try {
            // ตรวจสอบความซ้ำซ้อนของอีเมล (ต้องไม่ใช่ของคนอื่น)
            $stmtCheck = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ? AND id != ?");
            $stmtCheck->execute([$email, $userId]);
            if ($stmtCheck->fetchColumn() > 0) {
                $alertMessage = $at['err_email_exist'];
                $alertType = "error";
            } else {
                if (!empty($newPass)) {
                    if (strlen($newPass) < 6) {
                        $alertMessage = $at['err_password_len'];
                        $alertType = "error";
                    } else {
                        // อัปเดตรวมรหัสผ่านใหม่
                        $hashedPass = password_hash($newPass, PASSWORD_DEFAULT);
                        $stmtUpdate = $pdo->prepare("UPDATE users SET name = ?, email = ?, password = ? WHERE id = ?");
                        $stmtUpdate->execute([$name, $email, $hashedPass, $userId]);
                        
                        $alertMessage = $at['success_update'];
                        $alertType = "success";
                    }
                } else {
                    // อัปเดตเฉพาะชื่อและอีเมล
                    $stmtUpdate = $pdo->prepare("UPDATE users SET name = ?, email = ? WHERE id = ?");
                    $stmtUpdate->execute([$name, $email, $userId]);
                    
                    $alertMessage = $at['success_update'];
                    $alertType = "success";
                }

                if ($alertType === "success") {
                    // ปรับค่าในเซสชันตามความจริง
                    $_SESSION['username'] = $name;
                    $_SESSION['user_email'] = $email;
                    // อัปเดตข้อมูลตัวแปรแสดงผลหน้าจอด้วย
                    $user['name'] = $name;
                    $user['email'] = $email;
                }
            }
        } catch (PDOException $e) {
            $alertMessage = $at['err_db'] . $e->getMessage();
            $alertType = "error";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="<?= $lang ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= ($lang == 'th') ? 'บัญชีของฉัน' : 'My Profile' ?> - Noa Shop</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;800&family=Sarabun:wght@300;400;600;800&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Outfit', 'Sarabun', sans-serif; }
        .gradient-brand { background: linear-gradient(135deg, #f59e0b 0%, #ee4d2d 100%); }
        .text-gradient {
            background: linear-gradient(135deg, #f59e0b 0%, #ee4d2d 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
    </style>
</head>
<body class="<?= $tc['bg'] ?> min-h-screen antialiased flex flex-col justify-between transition-colors duration-300">

    <!-- NAVIGATION BAR -->
    <nav class="sticky top-0 z-50 backdrop-blur-md <?= $tc['navbar'] ?> py-4 px-6">
        <div class="max-w-7xl mx-auto flex justify-between items-center">
            <a href="index.php" class="text-2xl font-black text-gradient hover:scale-105 transform transition duration-200">
                Noa Shop
            </a>

            <div class="flex items-center space-x-4 text-sm font-semibold">
                <!-- สลับภาษา -->
                <a href="index.php?action=toggle_lang" class="px-2.5 py-1 border border-slate-400/30 rounded-md text-xs hover:bg-amber-500 hover:text-white transition duration-200">
                    🌐 <?= strtoupper($lang) ?>
                </a>

                <!-- สลับธีม -->
                <a href="index.php?action=toggle_theme" class="p-1.5 border border-slate-400/30 rounded-md text-xs hover:bg-amber-500 hover:text-white transition duration-200">
                    <?= ($theme == 'light') ? '🌙 Dark Mode' : '☀️ Light Mode' ?>
                </a>

                <a href="index.php" class="text-xs hover:underline transition">
                    <?= $at['back_to_shop'] ?>
                </a>
            </div>
        </div>
    </nav>

    <!-- MAIN GRID CONTAINER -->
    <main class="max-w-3xl mx-auto px-6 py-12 w-full flex-grow">
        
        <!-- Welcome header -->
        <header class="mb-8 text-center animate__animated animate__fadeIn">
            <h1 class="text-3xl font-black text-gradient uppercase tracking-tight"><?= $at['title'] ?></h1>
            <p class="text-xs opacity-60 mt-2 max-w-md mx-auto"><?= $at['desc'] ?></p>
        </header>

        <!-- Alert Notification -->
        <?php if ($alertMessage): ?>
            <div class="mb-6 p-4 rounded-2xl text-center shadow-md animate__animated animate__bounceIn font-bold text-xs <?= $alertType === 'success' ? 'bg-emerald-500 text-white' : 'bg-red-500 text-white' ?>">
                <?= htmlspecialchars($alertMessage) ?>
            </div>
        <?php endif; ?>

        <!-- Account Info & Form Card -->
        <div class="rounded-3xl p-8 <?= $tc['card'] ?> animate__animated animate__fadeInUp">
            
            <form action="my_account.php" method="POST" class="space-y-6 text-xs">
                
                <!-- Display ID & Role -->
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 pb-6 border-b border-slate-200/50">
                    <div>
                        <span class="block font-bold uppercase tracking-wider text-slate-400 mb-1">User ID (#)</span>
                        <span class="text-sm font-mono font-bold bg-slate-500/10 px-3 py-1.5 rounded-lg inline-block">#USER-<?= $user['id'] ?></span>
                    </div>
                    <div>
                        <span class="block font-bold uppercase tracking-wider text-slate-400 mb-1"><?= $at['lbl_role'] ?></span>
                        <?php 
                        $roleColor = 'bg-blue-150 text-blue-800';
                        $roleText = $at['lbl_role_buyer'];
                        if ($user['role'] === 'admin') {
                            $roleColor = 'bg-red-500 text-white font-bold animate-pulse';
                            $roleText = $at['lbl_role_admin'];
                        } elseif ($user['role'] === 'seller') {
                            $roleColor = 'bg-amber-500 text-white font-bold';
                            $roleText = $at['lbl_role_seller'];
                        }
                        ?>
                        <span class="text-xs font-semibold px-3 py-1.5 rounded-lg inline-block <?= $roleColor ?>">
                            <?= $roleText ?>
                        </span>
                    </div>
                </div>

                <!-- Editable Fields -->
                <div>
                    <label class="block font-bold text-slate-500 mb-2 uppercase tracking-wide"><?= $at['lbl_name'] ?></label>
                    <input type="text" name="name" required value="<?= htmlspecialchars($user['name']) ?>"
                           class="w-full p-3.5 rounded-2xl outline-none font-medium text-sm <?= $tc['input'] ?>">
                </div>

                <div>
                    <label class="block font-bold text-slate-500 mb-2 uppercase tracking-wide"><?= $at['lbl_email'] ?></label>
                    <input type="email" name="email" required value="<?= htmlspecialchars($user['email']) ?>"
                           class="w-full p-3.5 rounded-2xl outline-none font-medium text-sm <?= $tc['input'] ?>">
                </div>

                <div>
                    <label class="block font-bold text-slate-500 mb-2 uppercase tracking-wide"><?= $at['lbl_new_password'] ?></label>
                    <input type="password" name="new_password" placeholder="<?= $at['ph_new_password'] ?>"
                           class="w-full p-3.5 rounded-2xl outline-none font-medium text-sm <?= $tc['input'] ?>">
                </div>

                <!-- Action Button -->
                <div class="pt-4">
                    <button type="submit" name="update_profile"
                            class="w-full py-4 rounded-2xl font-bold bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 text-white shadow-lg shadow-orange-500/10 hover:shadow-orange-500/20 transition transform active:scale-95 text-xs uppercase tracking-wider">
                        🚀 <?= $at['btn_save'] ?>
                    </button>
                </div>

            </form>

        </div>

    </main>

    <!-- FOOTER -->
    <footer class="py-8 text-center text-xs <?= $tc['footer'] ?> transition-colors duration-300">
        <p class="font-bold text-amber-500 mb-1">Noa Shop Eco-System</p>
        <p class="opacity-50">© 2026 Noa Shop. Premium Streetwear & Minimalist Pre-Orders</p>
    </footer>

</body>
</html>
