<?php
header("Content-Type: application/json");
session_start();
require_once '../config/db.php'; // Ensure path to db.php is correct

// Capture POST data
$user_name = $_POST['user_name'] ?? '';
$password = $_POST['password'] ?? '';

// Basic validation
if(empty($user_name) || empty($password)) {
    echo json_encode(["success" => false, "message" => "Please enter both username and password."]);
    exit();
}

try {
    // 1. Prepare query to fetch the staff record
    $stmt = $conn->prepare("SELECT id, user_name, password, role FROM team_grovia WHERE user_name = ? LIMIT 1");
    $stmt->bind_param("s", $user_name);
    $stmt->execute();
    $result = $stmt->get_result();

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

        // 2. Verify the hashed password against the user's input
        if(password_verify($password, $user['password'])) {
            
            // 3. Initiate the session and store essential staff data
            $_SESSION['team_id']   = $user['id'];
            $_SESSION['team_user'] = $user['user_name'];
            $_SESSION['team_role'] = $user['role'];

            echo json_encode(["success" => true, "message" => "Authentication successful. Redirecting..."]);
        } else {
            echo json_encode(["success" => false, "message" => "Invalid username or password."]);
        }
    } else {
        echo json_encode(["success" => false, "message" => "Invalid username or password."]);
    }

} catch (Exception $e) {
    echo json_encode(["success" => false, "message" => "System error. Please try again later."]);
}