<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 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);
}

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

// Load configuration
$configFile = __DIR__ . '/config.php';

if (!file_exists($configFile)) {
    die(json_encode(["status" => "error", "message" => "Config file not found."]));
}

$config = require $configFile;

if (!is_array($config) || !isset($config['aspfiy_api_secret'])) {
    die(json_encode(["status" => "error", "message" => "Invalid config file."]));
}

// Get API secret
$apiSecret = $config['aspfiy_api_secret'];

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

// Include functions file
require __DIR__ . '/functions.php';

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

    // Sanitize inputs
    $firstName = isset($data['firstName']) ? trim($data['firstName']) : '';
    $lastName = isset($data['lastName']) ? trim($data['lastName']) : '';
    $phone = isset($data['phone']) ? trim($data['phone']) : '';
    $email = isset($data['email']) ? trim($data['email']) : '';
    $password = isset($data['password']) ? trim($data['password']) : '';
    $confirmPassword = isset($data['confirm_password']) ? trim($data['confirm_password']) : '';
    $transactionPin = isset($data['transaction_pin']) ? trim($data['transaction_pin']) : '';

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

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(["status" => "error", "message" => "Invalid email format."]);
        exit();
    }

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

    // Validate transaction PIN (must be 4 digits)
    if (!preg_match('/^\d{4}$/', $transactionPin)) {
        echo json_encode(["status" => "error", "message" => "Transaction PIN must be 4 digits."]);
        exit();
    }

    // Check if password and confirm password match
    if ($password !== $confirmPassword) {
        echo json_encode(["status" => "error", "message" => "Passwords do not match."]);
        exit();
    }

    // Hash password and transaction PIN
    $hashedPassword = substr(hash('sha256', $password), 0, 10);
    $hashedTransactionPin = password_hash($transactionPin, PASSWORD_DEFAULT);

    // Check if email or phone already exists
    $checkQuery = "SELECT id FROM jamaa WHERE email = ? OR phone = ?";
    $checkStmt = $conn->prepare($checkQuery);
    $checkStmt->bind_param("ss", $email, $phone);
    $checkStmt->execute();
    $checkStmt->store_result();

    if ($checkStmt->num_rows > 0) {
        echo json_encode(["status" => "error", "message" => "Email or phone number already exists."]);
        exit();
    }
    $checkStmt->close();

    // Insert user data into the database
    $query = "INSERT INTO jamaa (firstName, lastName, email, phone, password, transaction_pin) VALUES (?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($query);

    try {
        $stmt->bind_param("ssssss", $firstName, $lastName, $email, $phone, $hashedPassword, $hashedTransactionPin);
        if ($stmt->execute()) {
            $userId = $stmt->insert_id; // Get the last inserted user ID

            // Create PalmPay account
            $palmPayResponse = createPalmPayAccount($firstName, $lastName, $email, $phone, $userId, $apiSecret);
            error_log("PalmPay Response: " . print_r($palmPayResponse, true));

            // Create Paga account
            $pagaResponse = createPagaAccount($firstName, $lastName, $email, $phone, $userId, $apiSecret);
            error_log("Paga Response: " . print_r($pagaResponse, true));

            // Extract account numbers
            $pagaAccountId = isset($pagaResponse['data']['account']['account_number']) ? $pagaResponse['data']['account']['account_number'] : null;
            $palmpayAccountId = isset($palmPayResponse['account_id']) ? $palmPayResponse['account_id'] : null;

            // Check if at least one account ID is available
            if ($pagaAccountId || $palmpayAccountId) {
                $updateQuery = "UPDATE jamaa SET palmpay_account_id = ?, paga_account_id = ? WHERE id = ?";
                $updateStmt = $conn->prepare($updateQuery);
                $updateStmt->bind_param("ssi", $palmpayAccountId, $pagaAccountId, $userId);

                if ($updateStmt->execute()) {
                    error_log("✅ Account IDs updated successfully for user ID: " . $userId);
                    echo json_encode(["status" => "success", "message" => "Registration and account creation successful!"]);
                } else {
                    error_log("❌ Failed to update account IDs: " . $updateStmt->error);
                    echo json_encode(["status" => "error", "message" => "Failed to update account IDs."]);
                }

                $updateStmt->close();
            } else {
                error_log("❌ No account ID available for update.");
                echo json_encode(["status" => "error", "message" => "Account creation failed."]);
            }
        } else {
            echo json_encode(["status" => "error", "message" => "Registration failed. Please try again."]);
        }
    } catch (mysqli_sql_exception $e) {
        echo json_encode(["status" => "error", "message" => "Error: " . $e->getMessage()]);
    }

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





















<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// Include the config.php file
$configFile = __DIR__ . '/config.php';

if (!file_exists($configFile)) {
    echo json_encode(["status" => "error", "message" => "Config file not found."]);
    exit();
}

$config = require $configFile;

// Debugging: Check the value and type of $config
if (!is_array($config)) {
    echo json_encode(["status" => "error", "message" => "Config file must return an array."]);
    exit();
}

// Access the API secret key
if (!isset($config['aspfiy_api_secret'])) {
    echo json_encode(["status" => "error", "message" => "API secret key not found in config."]);
    exit();
}

$apiSecret = $config['aspfiy_api_secret'];

// Include the functions.php file
require __DIR__ . '/functions.php';

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

    // Sanitize inputs
    $firstName = isset($data['firstName']) ? trim($data['firstName']) : '';
    $lastName = isset($data['lastName']) ? trim($data['lastName']) : '';
    $phone = isset($data['phone']) ? trim($data['phone']) : '';
    $email = isset($data['email']) ? trim($data['email']) : '';
    $password = isset($data['password']) ? trim($data['password']) : '';
    $confirmPassword = isset($data['confirm_password']) ? trim($data['confirm_password']) : '';
    $transactionPin = isset($data['transaction_pin']) ? trim($data['transaction_pin']) : '';
    $bankName = isset($data['bank_name']) ? trim($data['bank_name']) : '';
    $accountNumber = isset($data['account_number']) ? trim($data['account_number']) : '';

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

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(["status" => "error", "message" => "Invalid email format."]);
        exit();
    }

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

    // Validate transaction PIN (must be 4 digits)
    if (!preg_match('/^\d{4}$/', $transactionPin)) {
        echo json_encode(["status" => "error", "message" => "Transaction PIN must be 4 digits."]);
        exit();
    }

    // Check if password and confirm password match
    if ($password !== $confirmPassword) {
        echo json_encode(["status" => "error", "message" => "Passwords do not match."]);
        exit();
    }

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

    // Hash the transaction PIN securely
    $hashedTransactionPin = password_hash($transactionPin, PASSWORD_DEFAULT);

    // Insert user data into the database (example using MySQLi)
    $conn = new mysqli("localhost", "username", "password", "database");

    if ($conn->connect_error) {
        echo json_encode(["status" => "error", "message" => "Database connection failed."]);
        exit();
    }

    // Check if email or phone already exists
    $checkQuery = "SELECT id FROM jamaa WHERE email = ? OR phone = ?";
    $checkStmt = $conn->prepare($checkQuery);
    $checkStmt->bind_param("ss", $email, $phone);
    $checkStmt->execute();
    $checkStmt->store_result();

    if ($checkStmt->num_rows > 0) {
        echo json_encode(["status" => "error", "message" => "Email or phone number already exists."]);
        exit();
    }
    $checkStmt->close();

    // Insert user data into the database
    $query = "INSERT INTO jamaa (firstName, lastName, email, phone, password, transaction_pin, bank_name, account_number) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($query);

    try {
        $stmt->bind_param("ssssssss", $firstName, $lastName, $email, $phone, $hashedPassword, $hashedTransactionPin, $bankName, $accountNumber);
        if ($stmt->execute()) {
            $userId = $stmt->insert_id; // Get the last inserted user ID

            // Create PalmPay account
            $palmPayResponse = createPalmPayAccount($firstName, $lastName, $email, $phone, $userId, $apiSecret);
            file_put_contents('palmpay_response.log', print_r($palmPayResponse, true)); // Log the response

            // Create Paga account
            $pagaResponse = createPagaAccount($firstName, $lastName, $email, $phone, $userId, $apiSecret);
            file_put_contents('paga_response.log', print_r($pagaResponse, true)); // Log the response

            // Check if both accounts were created successfully
            if ($palmPayResponse && isset($palmPayResponse['account_id']) && $pagaResponse && isset($pagaResponse['account_id'])) {
                $palmpayAccountId = $palmPayResponse['account_id'];
                $pagaAccountId = $pagaResponse['account_id'];

                // Update the user record with PalmPay and Paga account IDs
                $updateQuery = "UPDATE jamaa SET palmpay_account_id = ?, paga_account_id = ? WHERE id = ?";
                $updateStmt = $conn->prepare($updateQuery);
                $updateStmt->bind_param("ssi", $palmpayAccountId, $pagaAccountId, $userId);

                if ($updateStmt->execute()) {
                    echo json_encode(["status" => "success", "message" => "Registration and account creation successful!"]);
                } else {
                    echo json_encode(["status" => "error", "message" => "Failed to update account IDs."]);
                }

                $updateStmt->close();
            } else {
                echo json_encode(["status" => "error", "message" => "Registration successful, but account creation failed."]);
            }
        } else {
            echo json_encode(["status" => "error", "message" => "Registration failed. Please try again."]);
        }
    } catch (mysqli_sql_exception $e) {
        echo json_encode(["status" => "error", "message" => "Error: " . $e->getMessage()]);
    }

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