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

// Include database connection
require_once '../../config.php';

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

// Get POST data
$identifier     = isset($_POST['identifier']) ? trim($_POST['identifier']) : '';
$password       = isset($_POST['password']) ? $_POST['password'] : '';
$isPhoneLogin   = isset($_POST['isPhoneLogin']) ? $_POST['isPhoneLogin'] : 'true';

// Validate inputs
if (empty($identifier) || empty($password)) {
    echo json_encode(["success" => false, "message" => "Please fill all fields"]);
    exit;
}

// Prepare query
if ($isPhoneLogin === 'true') {
    $sql = "SELECT id, branch_id, firstname, middlename, lastname, phone, email, password FROM customers WHERE phone = ?";
} else {
    $sql = "SELECT id, branch_id, firstname, middlename, lastname, phone, email, password FROM customers WHERE email = ?";
}

$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo json_encode(["success" => false, "message" => "Database query failed"]);
    exit;
}

$stmt->bind_param('s', $identifier);
$stmt->execute();
$result = $stmt->get_result();

// Check if user exists
if ($result->num_rows === 0) {
    echo json_encode(["success" => false, "message" => "User not found"]);
    exit;
}

$user = $result->fetch_assoc();
$stmt->close();

// Check password (plain text)
if (trim($password) === trim($user['password'])) {
    echo json_encode([
        "success"    => true,
        "message"    => "Login successful",
        "id"         => $user['id'],
        "branch_id"  => $user['branch_id'], 
        "firstname"  => $user['firstname'],
        "middlename" => $user['middlename'],
        "lastname"   => $user['lastname'],
        "phone"      => $user['phone'],
        "email"      => $user['email']
    ]);
} else {
    echo json_encode(["success" => false, "message" => "Incorrect password"]);
}

$conn->close();
?>
