<?php
// Allow CORS requests
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

// Include database connection file (your file uses $conn)
require_once '../config.php';

// Only accept POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(["success" => false, "message" => "Invalid request method"]);
    exit;
}

// Get raw POST values safely
$identifier = isset($_POST['identifier']) ? trim($_POST['identifier']) : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$isPhoneLoginRaw = isset($_POST['isPhoneLogin']) ? $_POST['isPhoneLogin'] : 'false';

// Normalize isPhoneLogin (accept 'true','1',1,true)
$isPhoneLogin = ($isPhoneLoginRaw === true) || $isPhoneLoginRaw === 'true' || $isPhoneLoginRaw === '1' || $isPhoneLoginRaw === 1;

if ($identifier === '' || $password === '') {
    echo json_encode(["success" => false, "message" => "Missing identifier or password"]);
    exit;
}

// Prepare SQL to fetch firstname and lastname (and other fields)
if ($isPhoneLogin) {
    $sql = "SELECT id, firstname, lastname, password, type, branch_id FROM users WHERE phone = ?";
} else {
    $sql = "SELECT id, firstname, lastname, password, type, branch_id FROM users WHERE email = ?";
}

if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param('s', $identifier);
    $stmt->execute();
    $result = $stmt->get_result();

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

        // Verify password (assuming passwords are hashed with password_hash)
        if (password_verify($password, $user['password'])) {
            $firstname = isset($user['firstname']) ? trim($user['firstname']) : '';
            $lastname = isset($user['lastname']) ? trim($user['lastname']) : '';
            $fullname = trim($firstname . ' ' . $lastname);

            $response = [
                "success" => true,
                "message" => "Login successful",
                "user_id" => (int)$user['id'],
                "user_type" => isset($user['type']) ? (int)$user['type'] : 0,
                "user_name" => $fullname,
                "branch_id" => isset($user['branch_id']) ? $user['branch_id'] : null
            ];

            echo json_encode($response);
        } else {
            echo json_encode(["success" => false, "message" => "Incorrect password"]);
        }
    } else {
        echo json_encode(["success" => false, "message" => "User not found"]);
    }

    $stmt->close();
} else {
    echo json_encode(["success" => false, "message" => "Database query failed"]);
}

$conn->close();
