<?php
session_start();
require_once "db_connect.php";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $username = $_POST["username"] ?? "";
    $password = $_POST["password"] ?? "";

    $stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();

        if (password_verify($password, $user["password"])) {

         if ($user["role"] !== "superadmin" && (int)$user["email_verified"] !== 1) {
                echo "<script>
                    alert('Please verify your email first.');
                    window.location.href = '../html/index.php';
                </script>";
                exit();
            }
    


            if ($user["status"] === "pending") {
    echo "<script>
        alert('Your account is waiting for approval.');
        window.location.href = '../html/index.php';
    </script>";
    exit();
}

            if ($user["status"] === "rejected") {
    echo "<script>
        alert('Your account was rejected.');
        window.location.href = '../html/index.php';
    </script>";
    exit();
}

            $_SESSION["user_id"] = $user["id"];
            $_SESSION["first_name"] = $user["first_name"];
            $_SESSION["last_name"] = $user["last_name"];
            $_SESSION["shop_name"] = $user["shop_name"];
            $_SESSION["mobile_number"] = $user["mobile_number"];
              $_SESSION["email"] = $user["email"];
            $_SESSION["role"] = $user["role"];

            if ($user["role"] === "admin") {
                header("Location: ../html/admin.php");
                exit();
            } elseif ($user["role"] === "customer") {
                header("Location: ../html/customer.php");
                exit();
            } elseif ($user["role"] === "superadmin") {
                header("Location: ../html/superadmin.php");
                exit();
            }
        } else {
            
            echo "<script>
    alert('Incorrect password.');
    window.location.href = '../html/index.php';
</script>";
exit();
        }
    } else {
       
        echo "<script>
    alert('User not found.');
    window.location.href = '../html/index.php';
</script>";
exit();
    }

    $stmt->close();
    $conn->close();
}
?>