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

// Start output buffering
ob_start();

// Set the content type to JSON
header("Content-Type: application/json");

function logError($message) {
    error_log(date('[Y-m-d H:i:s] ') . $message . PHP_EOL, 3, 'palmpay_error.log');
}

$response = ['success' => false, 'error' => 'Unknown error occurred'];

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Method Not Allowed');
    }

    // Get user details from POST data and validate
    $fname = filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING);
    $lname = filter_input(INPUT_POST, 'lastname', FILTER_SANITIZE_STRING);
    $phone = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING);
    $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

    if (!$email) {
        throw new Exception('Invalid email');
    }

    if (!$fname || !$lname || !$phone) {
        throw new Exception('Missing required fields');
    }

    // Log received data
    logError("Received data: " . json_encode($_POST));

    // Database connection function
    function connect() {
        $host = 'localhost';
        $dbname = 'netwvomn_aidata';
        $user = 'netwvomn_twesdaco';
        $password = 'TazTUTIvOVxu';

        try {
            $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $dbh;
        } catch (PDOException $e) {
            throw new Exception('Database connection failed: ' . $e->getMessage());
        }
    }

    // Billstack API function
    function generatePalmpayAccount($fname, $lname, $phone, $email) {
        $billstackSecret = 'Bill_Stack-SEC-KEY-08c6ba996a0822b98f093f0859326462';
        $url = 'https://api.billstack.co/v2/thirdparty/generateVirtualAccount/';
        $ref = str_shuffle(substr("ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz1234567890", 0, 12));

        $postData = json_encode([
            "reference" => $ref,
            "email" => $email,
            "firstName" => $fname,
            "lastName" => $lname,
            "phone" => $phone,
            "bank" => "PALMPAY"
        ]);

        logError("Sending request to Billstack: " . $postData);

        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $postData,
            CURLOPT_HTTPHEADER => array(
                "Authorization: Bearer " . $billstackSecret,
                "Content-Type: application/json"
            ),
        ));

        $result = curl_exec($ch);
        $err = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($err) {
            logError("cURL Error: " . $err);
            throw new Exception('cURL Error: ' . $err);
        }

        logError("Billstack response (HTTP $httpCode): " . $result);

        $decodedResult = json_decode($result, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('Invalid JSON response from Billstack: ' . json_last_error_msg());
        }

        return $decodedResult;
    }

    // Get user details from database
    $dbh = connect();
    $stmt = $dbh->prepare("SELECT sId, sPalmpayBank FROM subscribers WHERE sEmail = :email");
    $stmt->bindParam(':email', $email, PDO::PARAM_STR);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        throw new Exception('User not found');
    }

    // Check if user already has a PalmPay account
    if (!empty($user['sPalmpayBank'])) {
        $response = ['success' => true, 'message' => 'User already has a PalmPay account', 'account_number' => $user['sPalmpayBank']];
    } else {
        // Generate PalmPay account
        $palmpayResponse = generatePalmpayAccount($fname, $lname, $phone, $email);

        if (isset($palmpayResponse['data']['account'][0]['account_number'])) {
            $palmpayAccount = $palmpayResponse['data']['account'][0]['account_number'];

            // Update user's record with new PalmPay account number
            $updateStmt = $dbh->prepare("UPDATE subscribers SET sPalmpayBank = :account WHERE sEmail = :email");
            $updateStmt->bindParam(':account', $palmpayAccount, PDO::PARAM_STR);
            $updateStmt->bindParam(':email', $email, PDO::PARAM_STR);
            
            if ($updateStmt->execute()) {
                $response = ['success' => true, 'message' => 'PalmPay account created successfully', 'account_number' => $palmpayAccount];
            } else {
                throw new Exception('Failed to update user record');
            }
        } else {
            throw new Exception('Failed to generate PalmPay account: ' . json_encode($palmpayResponse));
        }
    }
} catch (Exception $e) {
    logError($e->getMessage());
    $response = ['success' => false, 'error' => $e->getMessage()];
}

// Clear the output buffer
$output = ob_get_clean();

// If there was any output, log it
if (!empty($output)) {
    logError("Unexpected output before JSON: " . $output);
}

// Log the response we're about to send
logError("Response to be sent: " . json_encode($response));

// Output the JSON response
echo json_encode($response);
exit;
?>