<?php

session_start();

include "../config/database.php";

if ($_SERVER["REQUEST_METHOD"] != "POST") {

    header("Location: ../login.php");
    exit();

}

$phone = trim($_POST['phone']);
$password = $_POST['password'];

$_SESSION['old'] = [

    'phone' => $phone

];

if (empty($phone) || empty($password)) {

    $_SESSION['error'] = "Please enter your phone number and password.";

    header("Location: ../login.php");
    exit();

}


// Check if Number Exists

$sql = "SELECT * FROM users WHERE phone = ?";

$stmt = $pdo->prepare($sql);

$stmt->execute([$phone]);

$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {

    $_SESSION['error'] = "Phone number not found.";

    header("Location: ../login.php");
    exit();

}

// Verify Password

if (!password_verify($password, $user['password'])) {

    $_SESSION['error'] = "Incorrect password.";

    header("Location: ../login.php");

    exit();

}

// Check Account Status

if ($user['status'] == "pending") {

    $_SESSION['error'] = "Your account is awaiting administrator approval.";

    header("Location: ../login.php");
    exit();

}

if ($user['status'] == "suspended") {

    $_SESSION['error'] = "Your account has been suspended.";

    header("Location: ../login.php");
    exit();

}

// LOGIN SUCCESSFUL

$_SESSION['logged_in'] = true;

$_SESSION['user_id'] = $user['id'];

$_SESSION['fullname'] = $user['fullname'];

$_SESSION['email'] = $user['email'];

$_SESSION['phone'] = $user['phone'];

$_SESSION['role'] = $user['role'];

$_SESSION['status'] = $user['status'];

// Clear old login email

unset($_SESSION['old']);

// Redirect based on role

// Redirect based on role

if ($user['role'] == "admin") {

    header("Location: ../admin/dashboard.php");

} else {

    header("Location: ../member/dashboard.php");

}

exit();