<?php
header("Content-Type: application/json");

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

// Read and decode the raw POST input
$data = json_decode(file_get_contents("php://input"), true);

// Validate required fields
if (!isset($data['email']) || !isset($data['password'])) {
    http_response_code(400);
    echo json_encode([
        "status" => false,
        "message" => "Email and password are required."
    ]);
    exit();
}

$email = mysqli_real_escape_string($con, $data['email']);
$password = md5($data['password']);

// Step 1: Check user credentials
$userQuery = "SELECT id, pid, name, email, au FROM users WHERE email='$email' AND password='$password'";
$userResult = mysqli_query($con, $userQuery);

if ($userRow = mysqli_fetch_assoc($userResult)) {
    $pid = $userRow['pid'];

    // Step 2: Get police details using pid
    $policeQuery = "SELECT id, pid, i_name, i_number, i_designation, i_sign FROM police WHERE pid='$pid'";
    $policeResult = mysqli_query($con, $policeQuery);

    $policeData = null;
    $stationData = null;

    if ($policeRow = mysqli_fetch_assoc($policeResult)) {
        $policeData = $policeRow;

        // Step 3: Get police station details using police.pid → policestation.id
        $stationQuery = "SELECT id, spid, p_name, p_address, p_landline, p_number, p_email, timestamp FROM policestation WHERE id='" . $policeRow['pid'] . "'";
        $stationResult = mysqli_query($con, $stationQuery);

        if ($stationRow = mysqli_fetch_assoc($stationResult)) {
            $stationData = $stationRow;
        }
    }

    // Final JSON response
    echo json_encode([
        "status" => true,
        "message" => "Login successful",
        "user" => $userRow,
        "police" => $policeData,
        "station" => $stationData
    ]);
} else {
    echo json_encode([
        "status" => false,
        "message" => "Invalid email or password"
    ]);
}
?>