<?php
session_start();

$host   = "webdev.iyaserver.com";
$userid = "dhreid_guest";
$userpw = "tPTG;A+J{]Ze";
$db     = "dhreid_marketplace";

$mysql = new mysqli($host, $userid, $userpw, $db);
if ($mysql->connect_errno) {
    die("DB connection error: " . $mysql->connect_error);
}

// ✅ LOGIN REQUIRED
if (!isset($_SESSION['user_id'])) {
    header("Location: loginPage.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$error = "";
$success = "";

// ✅ HANDLE PROFILE UPDATE
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

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

    if ($fullName === "" || $handle === "" || $phone === "") {
        $error = "All fields are required.";
    } else {

        // ✅ Prevent duplicate usernames
        $check = $mysql->prepare("
            SELECT user_id 
            FROM users 
            WHERE handle = ? AND user_id != ?
        ");
        $check->bind_param("si", $handle, $user_id);
        $check->execute();
        $res = $check->get_result();

        if ($res && $res->fetch_assoc()) {
            $error = "That username is already taken.";
        } else {

            // ✅ UPDATE USER PROFILE
            $stmt = $mysql->prepare("
                UPDATE users 
                SET full_name = ?, handle = ?, phone = ?
                WHERE user_id = ?
            ");
            $stmt->bind_param("sssi", $fullName, $handle, $phone, $user_id);

            if ($stmt->execute()) {
                $success = "Profile updated successfully!";
            } else {
                $error = "Update failed.";
            }
        }
    }
}

// ✅ FETCH USER DATA
$stmt = $mysql->prepare("
    SELECT full_name, usc_email, handle, phone, created_at, trust_score
    FROM users
    WHERE user_id = ?
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-FEM3Q0G7NZ"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'G-FEM3Q0G7NZ');
    </script>
    <meta charset="UTF-8">
    <title>My Account</title>
    <link rel="stylesheet" href="stylesheet.css">

    <!-- ✅ GOOGLE ANALYTICS -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-FEM3Q0G7NZ"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'G-FEM3Q0G7NZ');
    </script>

    <style>
        body {
            font-family: Montserrat, system-ui, sans-serif;
            background:#f9fafb;
            display:flex;
            justify-content:center;
            align-items:center;
            min-height:100vh;
        }

        .account-card {
            background:white;
            width:420px;
            padding:40px;
            border-radius:20px;
            box-shadow: 0 10px 25px rgba(0,0,0,.12);
        }

        h2 {
            color:#990000;
            text-align:center;
            margin-bottom:24px;
        }

        label {
            font-size:14px;
            font-weight:600;
            color:#990000;
        }

        input {
            width:100%;
            padding:10px;
            margin-top:4px;
            margin-bottom:14px;
            border-radius:12px;
            border:1.5px solid #990000;
            outline:none;
        }

        button {
            width:100%;
            padding:12px;
            border-radius:14px;
            border:none;
            background:#990000;
            color:white;
            font-weight:600;
            cursor:pointer;
        }

        .meta {
            font-size:13px;
            color:#555;
            margin-bottom:12px;
        }

        .error-box {
            color:#b91c1c;
            font-size:14px;
            margin-bottom:12px;
            text-align:center;
        }

        .success-box {
            color:#166534;
            font-size:14px;
            margin-bottom:12px;
            text-align:center;
        }

        .logout {
            margin-top:18px;
            text-align:center;
        }
    </style>
</head>
<body>

<div class="account-card">
    <h2>My Account</h2>

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

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

    <form method="POST">

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

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

        <label>Phone</label>
        <input type="text" name="phone" value="<?= htmlspecialchars($user['phone']) ?>">

        <label>USC Email (cannot change)</label>
        <input type="email" value="<?= htmlspecialchars($user['usc_email']) ?>" disabled>

        <div class="meta">
            Member Since: <?= htmlspecialchars($user['created_at']) ?><br>
            Trust Score: <?= htmlspecialchars($user['trust_score']) ?>
        </div>

        <button type="submit">Save Changes</button>
    </form>

    <div class="logout">
        <a href="logout.php">Log Out</a>
    </div>
</div>

</body>
</html>
