<?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);
}

$error   = "";
$success = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // 1. Grab form values
    $fullName = trim($_POST['full_name'] ?? "");
    $email    = trim($_POST['usc_email'] ?? "");
    $handle   = trim($_POST['handle'] ?? "");
    $phone    = trim($_POST['phone'] ?? "");
    $password = trim($_POST['password'] ?? "");
    $confirm  = trim($_POST['confirm_password'] ?? "");

    // handle and username are the same value
    $username = $handle;

    // 2. Basic validation
    if ($fullName === "" || $email === "" || $handle === "" || $phone === "" || $password === "" || $confirm === "") {
        $error = "Please fill out all fields.";
    }
    elseif (!preg_match("/@usc\.edu$/i", $email)) {
        $error = "Please use your USC email address.";
    }
    elseif ($password !== $confirm) {
        $error = "Password and Confirm Password must match.";
    } else {

        // 3. Check if an account already exists with that email
        $check = $mysql->prepare(
            "SELECT user_id 
             FROM users 
             WHERE usc_email = ?
             LIMIT 1"
        );
        if (!$check) {
            $error = "Prepare failed (check): " . $mysql->error;
        } else {
            $check->bind_param("s", $email);
            $check->execute();
            $result = $check->get_result();

            if ($result && $result->fetch_assoc()) {
                $error = "An account with that USC email already exists.";
            } else {

                // 4. Insert new user into users table
                // Columns: user_id, full_name, usc_email, handle, phone, username, password, is_admin, created_at, trust_score
                $stmt = $mysql->prepare(
                    "INSERT INTO users
                     (full_name, usc_email, handle, phone, password)
                     VALUES (?, ?, ?, ?, ?)"
                );

                if (!$stmt) {
                    $error = "Prepare failed (insert): " . $mysql->error;
                } else {
                    $stmt->bind_param ("sssss", $fullName, $email, $handle, $phone, $password);
                    $ok = $stmt->execute();

                    if (!$ok) {
                        $error = "Error creating account: " . $stmt->error;
                    } else {
                        $success = "Account created successfully! You can now log in with: " . htmlspecialchars($email);
                        // If you want to debug the ID: uncomment next line
                        // $success .= " (user_id = " . $mysql->insert_id . ")";
                    }
                }
            }
        }
    }
}
?>
<!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>USC Marketplace Sign up</title>

    <!-- CSS FILE -->
    <link rel="stylesheet" href="stylesheet.css">

    <!-- FONT -->
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600;700&display=swap" rel="stylesheet">

    <style>
        body {
            margin: 0;
            font-family: "Montserrat", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
            background: #ffffff;
            display:flex;
            align-items:center;
            justify-content:center;
            background-image:
                    linear-gradient(to right, rgba(153,0,0,0.05) 1px, transparent 1px),
                    linear-gradient(to bottom, rgba(153,0,0,0.05) 1px, transparent 1px);
            background-size: 40px 40px;
        }

        #topBanner {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 90%;
            height: fit-content;
            margin: 30px;
            border-radius: 10px;
        }

        .main-title {
            font-size: 3em;
            font-weight: 700;
            text-align: center;
            color: #990000;
            letter-spacing: 2px;
        }

        .page-wrapper {
            width:80%;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px 20px;
        }

        .pageWrapper {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .login-card {
            display: flex;
            width: 950px;
            height: fit-content;
            border-radius: 32px;
            overflow: hidden;
            background-color: #990000;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            margin-bottom: 50px;
        }

        .login-left {
            flex: 2;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 40px;
            height: fit-content;
        }

        .login-panel {
            width: 90%;
            display: flex;
            align-items: center;
            justify-content: center;
            max-width: 700px;
            background: white;
            border-radius: 26px;
            padding: 50px;
            height: 90%;
            margin: 30px;
            flex-direction: column;
            text-align: left;
        }

        .login-title {
            text-align: center;
            margin: 0 0 40px;
            font-size: 26px;
            letter-spacing: 2px;
            color: #990000;
        }

        .login-form {
            display: flex;
            flex-direction: column;
            gap: 18px;
        }

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

        .login-form input {
            margin-top: 4px;
            width: 350px;
            padding: 10px 14px;
            border-radius: 18px;
            border: 2px solid #990000;
            font-size: 14px;
            outline: none;
        }

        .login-form input:focus {
            box-shadow: 0 0 0 2px rgba(127, 35, 27, 0.2);
        }

        .btn-signin {
            align-self: center;
            margin-top: 24px;
            padding: 10px 36px;
            border-radius: 18px;
            border: none;
            background-color: #990000;
            color: white;
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
        }

        .btn-signin:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .create-link {
            margin-top: 14px;
            font-size: 14px;
            color: #990000;
            text-decoration: none;
        }

        .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;
        }

        .login-right {
            width:400px;
            height:auto;
            background: #FFC72C;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .peace-img {
            max-width: 90%;
            height: auto;
            transition: transform 0.3s ease, filter 0.3s ease;
        }

        .peace-img:hover {
            transform: scale(1.08);
            filter: brightness(1.15);
        }

        .peace-img {
            cursor: pointer;
            transition: transform 0.4s ease;
            transform-origin: center;
        }

        .peace-img.animate {
            transform: rotate(20deg) scale(1.25);
        }

        .password-hint {
            font-size: 12px;
            color: #b91c1c;
            min-height: 16px;
        }

        @media (max-width: 800px) {
            .login-card {
                flex-direction: column;
                height: auto;
            }

            .login-right {
                padding: 30px 0;
            }

            .login-panel {
                padding: 40px 40px 30px;
            }
        }
    </style>
</head>

<body>

<div class="page-wrapper">
    <div class="pageWrapper">

        <!-- Banner -->
        <div id="topBanner">
            <h1 class="main-title">USC Student Marketplace</h1>
        </div>

        <!-- Signup Card -->
        <div class="login-card">

            <div class="login-left">
                <div class="login-panel">
                    <h1 class="login-title">CREATE NEW ACCOUNT</h1>

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

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

                    <form class="login-form" method="POST" id="signupForm">
                        <label for="full_name">Full Name</label>
                        <input type="text" name="full_name" id="full_name" placeholder="Jane Doe" required />

                        <label for="usc_email">USC Email</label>
                        <input type="email" name="usc_email" id="usc_email" placeholder="name@usc.edu" required />

                        <label for="handle">Username</label>
                        <input type="text" name="handle" id="handle" placeholder="@trojanSeller" required />

                        <label for="phone">Phone Number</label>
                        <input type="text" name="phone" id="phone" placeholder="123-456-7890" required />

                        <label for="password">Password</label>
                        <input type="password" name="password" id="password" required />

                        <label for="confirm_password">Confirm Password</label>
                        <input type="password" name="confirm_password" id="confirm_password" required />
                        <div id="passwordHint" class="password-hint"></div>

                        <button type="submit" class="btn-signin" id="submitBtn" disabled>CREATE ACCOUNT</button>
                    </form>

                    <!-- Link back to login page -->
                    <a href="loginPage.php" class="create-link">Back to Login</a>
                </div>
            </div>

            <div class="login-right">
                <img src="fightOn.png" alt="Fight On hand sign" class="peace-img" id="fightOnImg">
            </div>

        </div>
    </div>
</div>
<script>
    const fightOn = document.getElementById("fightOnImg");
    const password = document.getElementById("password");
    const confirmPassword = document.getElementById("confirm_password");
    const submitBtn = document.getElementById("submitBtn");
    const passwordHint = document.getElementById("passwordHint");

    fightOn.addEventListener("click", () => {
        fightOn.classList.add("animate");
        setTimeout(() => {
            fightOn.classList.remove("animate");
        }, 400);
    });

    function checkPasswords() {
        if (!password.value || !confirmPassword.value) {
            submitBtn.disabled = true;
            passwordHint.textContent = "";
            return;
        }

        if (password.value === confirmPassword.value) {
            submitBtn.disabled = false;
            passwordHint.textContent = "";
        } else {
            submitBtn.disabled = true;
            passwordHint.textContent = "Passwords do not match.";
        }
    }

    password.addEventListener("input", checkPasswords);
    confirmPassword.addEventListener("input", checkPasswords);
</script>

</body>
</html>