<?php
header("Content-Type: application/json");

// Enable error reporting for debugging (remove in production)
ini_set('display_errors', 1);
error_reporting(E_ALL);

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

// Ensure it's a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    exit;
}

// Validate and get email
$email = isset($_POST['email']) ? trim($_POST['email']) : '';

if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['error' => 'Invalid email']);
    exit;
}

// Database connection function
function connect() {
    $host = 'localhost';
    $dbname = 'u296133816_mdataplus';
    $user = 'u296133816_mdataplus';
    $password = 'O1v&aSO|';

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

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

    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 50,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode([
            "reference" => $ref,
            "email" => $email,
            "firstName" => $fname,
            "lastName" => $lname,
            "phone" => $phone,
            "bank" => "PALMPAY"
        ]),
        CURLOPT_HTTPHEADER => array(
            "Authorization: Bearer " . $billstackSecret,
            "Content-Type: application/json"
        ),
    ));

    $result = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);

    if ($err) {
        logError('cURL Error: ' . $err);
        return ['error' => 'cURL Error: ' . $err];
    }

    return json_decode($result, true);
}

try {
    // Connect to the database
    $dbh = connect();
    
    // Get user details using email
    $stmt = $dbh->prepare("SELECT sFname, sLname, sPhone, sPalmpayBank FROM subscribers WHERE sEmail = :email");
    $stmt->bindParam(':email', $email, PDO::PARAM_STR);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        echo json_encode(['error' => 'User not found']);
        exit;
    }

    // Check if PalmPay account already exists
    if (!empty($user['sPalmpayBank'])) {
        echo json_encode(['success' => true, 'message' => 'User already has a PalmPay account', 'account_number' => $user['sPalmpayBank']]);
        exit;
    }

    // Generate PalmPay account
    $palmpayResponse = generatePalmpayAccount($user['sFname'], $user['sLname'], $user['sPhone'], $email);

    // Check API response
    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()) {
            echo json_encode(['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());
    echo json_encode(['error' => $e->getMessage()]);
}
?>
