<?php
// Enable CORS
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

// Handle preflight request
if ($_SERVER["REQUEST_METHOD"] == "OPTIONS") {
    exit(0);
}

// Include the database connection file
require '../require/conn.php';

// Enable MySQLi error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Set headers to return JSON response
header('Content-Type: application/json');

// Handle login request
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the raw POST data
    $data = json_decode(file_get_contents('php://input'), true);

    // Sanitize inputs
    $phone = isset($data['phone']) ? trim($data['phone']) : '';
    $password = isset($data['password']) ? trim($data['password']) : '';

    // Validate input fields
    if (empty($phone) || empty($password)) {
        echo json_encode(["status" => "error", "message" => "All fields are required."]);
        exit();
    }

    // Validate phone number format
    if (!preg_match('/^\+?\d{8,15}$/', $phone)) {
        echo json_encode(["status" => "error", "message" => "Invalid phone number format."]);
        exit();
    }

    // Generate a 10-character hash for the password
    $hashedInputPassword = substr(hash('sha256', $password), 0, 10);

    try {
        // Fetch user data from the database
        $query = "SELECT id, firstName, lastName, email, phone, password FROM jamaa WHERE phone = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("s", $phone);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {
            $row = $result->fetch_assoc();
            $storedHashedPassword = $row['password'];

            // Verify the password
            if ($hashedInputPassword === $storedHashedPassword) {
                // Login successful
                echo json_encode([
                    "status" => "success",
                    "message" => "Login successful!",
                    "firstName" => $row['firstName'],
                    "lastName" => $row['lastName']
                ]);
            } else {
                // Invalid password
                echo json_encode(["status" => "error", "message" => "Invalid password."]);
            }
        } else {
            // User not found
            echo json_encode(["status" => "error", "message" => "User not found."]);
        }

        // Close the statement
        $stmt->close();
    } catch (Exception $e) {
        // Handle database errors
        echo json_encode(["status" => "error", "message" => "Database error: " . $e->getMessage()]);
    }

    // Close the database connection
    $conn->close();
    exit();
} else {
    // Invalid request method
    echo json_encode(["status" => "error", "message" => "Invalid request method."]);
    exit();
}
?>