<?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 dashboard 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']) : '';

    // Validate input fields
    if (empty($phone)) {
        echo json_encode(["status" => "error", "message" => "Phone number is required."]);
        exit();
    }

    try {
        // Fetch user data from the database
        $query = "SELECT firstName, lastName, wallet_balance 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();
            echo json_encode([
                "status" => "success",
                "firstName" => $row['firstName'],
                "lastName" => $row['lastName'],
                "wallet_balance" => $row['wallet_balance']
            ]);
        } 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();
}
?>