<?php
session_start();

require_once "../config/db.php";

/* =========================
   GET REDIRECT URL
========================= */
$redirect = $_GET['redirect'] ?? '';

/* =========================
   ALREADY LOGIN
========================= */
if (isset($_SESSION['user_id'])) {

    if (!empty($redirect)) {

        header("Location: " . $redirect);
        exit();
    }

    // guest manual open register page
    if ($_SESSION['role'] === 'guest') {

        header("Location: ../equipment/guest_home.php");
        exit();
    }

    // normal system user
    header("Location: ../dashboard.php");
    exit();
}

$message = "";
$error = "";

/* =========================
   REGISTER PROCESS
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $full_name       = trim($_POST['full_name']);
    $email           = trim($_POST['email']);
    $phone_number    = trim($_POST['phone_number']);
    $password        = trim($_POST['password']);
    $confirm_password= trim($_POST['confirm_password']);

    // IMPORTANT
    $redirect = $_POST['redirect'] ?? '';

    /* =========================
       VALIDATION
    ========================= */
    if (
        empty($full_name) ||
        empty($email) ||
        empty($password) ||
        empty($confirm_password)
    ) {

        $error = "Please fill all required fields.";

    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

        $error = "Invalid email format.";

    } elseif ($password !== $confirm_password) {

        $error = "Password does not match.";

    } elseif (strlen($password) < 6) {

        $error = "Password must be at least 6 characters.";

    } else {

        /* =========================
           CHECK EXISTING EMAIL
        ========================= */
        $check = mysqli_prepare($conn, "
            SELECT id 
            FROM users 
            WHERE email = ?
        ");

        mysqli_stmt_bind_param($check, "s", $email);
        mysqli_stmt_execute($check);

        $checkResult = mysqli_stmt_get_result($check);

        if (mysqli_num_rows($checkResult) > 0) {

            $error = "Email already registered.";

        } else {

            /* =========================
               HASH PASSWORD
            ========================= */
            $hashed_password = password_hash(
                $password,
                PASSWORD_DEFAULT
            );

            /* =========================
               INSERT GUEST USER
            ========================= */
            $insert = mysqli_prepare($conn, "
                INSERT INTO users
                (
                    full_name,
                    email,
                    phone_number,
                    password,
                    role
                )
                VALUES
                (
                    ?, ?, ?, ?, 'guest'
                )
            ");

            mysqli_stmt_bind_param(
                $insert,
                "ssss",
                $full_name,
                $email,
                $phone_number,
                $hashed_password
            );

            if (mysqli_stmt_execute($insert)) {

                $user_id = mysqli_insert_id($conn);

                /* =========================
                   AUTO LOGIN
                ========================= */
                $_SESSION['user_id'] = $user_id;
                $_SESSION['full_name'] = $full_name;
                $_SESSION['role'] = 'guest';
                $_SESSION['department_id'] = null;

                /* =========================
                   REDIRECT FLOW
                ========================= */

                // if came from QR equipment page
                if (!empty($redirect)) {

                    header("Location: " . $redirect);
                    exit();
                }

                // manual register
                header("Location: ../equipment/guest_home.php");
                exit();

            } else {

                $error = "Registration failed.";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>

    <title>Register Guest - QRCareTrack</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>

        *{
            box-sizing:border-box;
            font-family:'Segoe UI', sans-serif;
        }

        body{
            margin:0;
            min-height:100vh;

            background:
            url('../assets/background.png')
            no-repeat center center/cover;

            display:flex;
            justify-content:center;
            align-items:center;

            padding:20px;
        }

        .register-card{

            width:420px;
            max-width:100%;

            background:#fff;

            padding:40px 35px;

            border-radius:14px;

            box-shadow:0 15px 35px rgba(0,0,0,0.15);
        }

        .logo{
            width:80px;
            display:block;
            margin:0 auto 20px;
        }

        h2{
            text-align:center;
            margin-bottom:10px;
            color:#333;
        }

        .subtitle{
            text-align:center;
            color:#666;
            margin-bottom:25px;
            font-size:14px;
        }

        .form-group{
            margin-bottom:18px;
        }

        label{
            display:block;
            margin-bottom:6px;
            font-size:14px;
            color:#444;
            font-weight:600;
        }

        input{

            width:100%;

            padding:11px 12px;

            border:1px solid #ccc;

            border-radius:8px;

            font-size:14px;

            transition:0.2s;
        }

        input:focus{

            border-color:#2bbbad;
            outline:none;

            box-shadow:
            0 0 0 3px rgba(43,187,173,0.15);
        }

        .btn-register{

            width:100%;

            padding:12px;

            background:#2bbbad;

            border:none;

            border-radius:25px;

            color:white;

            font-size:15px;
            font-weight:600;

            cursor:pointer;

            transition:0.2s;
        }

        .btn-register:hover{
            background:#239c92;
        }

        .error{

            background:#ffe5e5;
            color:#c0392b;

            padding:10px;

            border-radius:8px;

            margin-bottom:15px;

            font-size:14px;
        }

        .login-link{

            margin-top:20px;

            text-align:center;

            font-size:14px;
        }

        .login-link a{
            color:#2bbbad;
            text-decoration:none;
            font-weight:600;
        }

        .login-link a:hover{
            text-decoration:underline;
        }

        @media(max-width:480px){

            .register-card{
                padding:30px 20px;
            }

        }

    </style>

</head>

<body>

<div class="register-card">

    <img
        src="../assets/logo.png"
        class="logo"
        alt="QRCareTrack Logo"
    >

    <h2>Create Guest Account</h2>

    <div class="subtitle">
        Register to report equipment issues
    </div>

    <?php if (!empty($error)): ?>

        <div class="error">
            <?= htmlspecialchars($error) ?>
        </div>

    <?php endif; ?>

    <form method="POST">

        <!-- IMPORTANT -->
        <input
            type="hidden"
            name="redirect"
            value="<?= htmlspecialchars($redirect) ?>"
        >

        <div class="form-group">

            <label>Full Name</label>

            <input
                type="text"
                name="full_name"
                required
            >

        </div>

        <div class="form-group">

            <label>Email Address</label>

            <input
                type="email"
                name="email"
                required
            >

        </div>

        <div class="form-group">

            <label>Phone Number</label>

            <input
                type="text"
                name="phone_number"
            >

        </div>

        <div class="form-group">

            <label>Password</label>

            <input
                type="password"
                name="password"
                required
            >

        </div>

        <div class="form-group">

            <label>Confirm Password</label>

            <input
                type="password"
                name="confirm_password"
                required
            >

        </div>

        <button
            type="submit"
            class="btn-register"
        >
            Register Account
        </button>

        <div class="login-link">

            Already have account?

            <a href="login.php?redirect=<?= urlencode($redirect) ?>">
                Login Here
            </a>

        </div>

    </form>

</div>

</body>
</html>