<?php
session_start();

// Make sure the user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

require 'require/conn.php';      // Database connection
require 'functions.php';         // Contains createPalmPayAccount & createPagaAccount

// API Secret (already set)
$apiSecret = 'Aspfiy-8fcf1b2ecf84e2dffa3388e4ded9c48a';

$userId = $_SESSION['user_id'];
$firstName = $_SESSION['firstName'];
$lastName = $_SESSION['lastName'];
$email = $_SESSION['email'];
$phone = $_SESSION['phone'];

// Check which account type was requested
if (!isset($_POST['account_type'])) {
    echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
    <script>
        Swal.fire({
            icon: 'error',
            title: 'No Account Type',
            text: 'No account type specified.'
        }).then(function() {
            window.location.href = 'account.php';
        });
    </script>";
    exit;
}

$accountType = $_POST['account_type'];
$response = null;

if ($accountType === 'palmpay') {

    // ✅ Check if Palmpay account already exists in the database
    $checkPalmpay = $conn->prepare("SELECT palmpay_account_no, palmpay_account_name FROM jamaa WHERE id = ?");
    $checkPalmpay->bind_param("i", $userId);
    $checkPalmpay->execute();
    $checkPalmpay->bind_result($existingAccountNo, $existingAccountName);
    $checkPalmpay->fetch();
    $checkPalmpay->close();

    if (!empty($existingAccountNo)) {
        // ✅ User already has a Palmpay account
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({
                icon: 'info',
                title: 'Account Already Exists',
                html: 'Palmpay account already exists.<br><strong>Account Name:</strong> {$existingAccountName}<br><strong>Account Number:</strong> {$existingAccountNo}'
            }).then(function() {
                window.location.href = 'account.php';
            });
        </script>";
        exit;
    }

    // ✅ Create a new Palmpay account if it doesn't exist
    $response = createPalmPayAccount($firstName, $lastName, $email, $phone, $userId, $apiSecret);

    if ($response && isset($response['status']) && $response['status'] == 1) {

        $accountNumber = $response['data']['account']['account_number'];
        $accountName   = $response['data']['account']['account_name'];

        $stmt = $conn->prepare("UPDATE jamaa SET palmpay_account_no = ?, palmpay_account_name = ? WHERE id = ?");
        $stmt->bind_param("ssi", $accountNumber, $accountName, $userId);

        if ($stmt->execute()) {
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({
                    icon: 'success',
                    title: 'Palmpay Account Created',
                    html: '<strong>Account Name:</strong> {$accountName}<br><strong>Account Number:</strong> {$accountNumber}'
                }).then(function() {
                    window.location.href = 'account.php';
                });
            </script>";
            exit;
        } else {
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({
                    icon: 'error',
                    title: 'Database Error',
                    text: 'Failed to update Palmpay account in database.'
                }).then(function() {
                    window.location.href = 'account.php';
                });
            </script>";
            exit;
        }

    } else {
        $errorMessage = isset($response['message']) ? $response['message'] : 'Unknown error';
        // ✅ Specific handling for "Reference already exists"
        if (strpos($errorMessage, 'Reference already exists') !== false) {
            $errorMessage = 'You already have a Palmpay account.';
        }

        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({
                icon: 'error',
                title: 'Failed to create Palmpay account',
                text: '{$errorMessage}'
            }).then(function() {
                window.location.href = 'account.php';
            });
        </script>";
        exit;
    }

} elseif ($accountType === 'paga') {

    // ✅ Check if Paga account already exists in the database
    $checkPaga = $conn->prepare("SELECT paga_account_id, paga_account_name FROM jamaa WHERE id = ?");
    $checkPaga->bind_param("i", $userId);
    $checkPaga->execute();
    $checkPaga->bind_result($existingPagaId, $existingPagaName);
    $checkPaga->fetch();
    $checkPaga->close();

    if (!empty($existingPagaId)) {
        // ✅ User already has a Paga account
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({
                icon: 'info',
                title: 'Account Already Exists',
                html: 'Paga account already exists.<br><strong>Account Name:</strong> {$existingPagaName}<br><strong>Account Number:</strong> {$existingPagaId}'
            }).then(function() {
                window.location.href = 'account.php';
            });
        </script>";
        exit;
    }

    // ✅ Create a new Paga account if it doesn't exist
    $response = createPagaAccount($firstName, $lastName, $email, $phone, $userId, $apiSecret);

    if ($response && isset($response['status']) && $response['status'] == 1) {

        $accountNumber = $response['data']['account']['account_number'];
        $accountName   = $response['data']['account']['account_name'];

        $stmt = $conn->prepare("UPDATE jamaa SET paga_account_id = ?, paga_account_name = ? WHERE id = ?");
        $stmt->bind_param("ssi", $accountNumber, $accountName, $userId);

        if ($stmt->execute()) {
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({
                    icon: 'success',
                    title: 'Paga Account Created',
                    html: '<strong>Account Name:</strong> {$accountName}<br><strong>Account Number:</strong> {$accountNumber}'
                }).then(function() {
                    window.location.href = 'account.php';
                });
            </script>";
            exit;
        } else {
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({
                    icon: 'error',
                    title: 'Database Error',
                    text: 'Failed to update Paga account in database.'
                }).then(function() {
                    window.location.href = 'account.php';
                });
            </script>";
            exit;
        }

    } else {
        $errorMessage = isset($response['message']) ? $response['message'] : 'Unknown error';
        // ✅ Specific handling for "Reference already exists"
        if (strpos($errorMessage, 'Reference already exists') !== false) {
            $errorMessage = 'You already have a Paga account.';
        }

        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({
                icon: 'error',
                title: 'Failed to create Paga account',
                text: '{$errorMessage}'
            }).then(function() {
                window.location.href = 'account.php';
            });
        </script>";
        exit;
    }

} else {
    echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
    <script>
        Swal.fire({
            icon: 'error',
            title: 'Invalid Account Type',
            text: 'The account type provided is invalid.'
        }).then(function() {
            window.location.href = 'account.php';
        });
    </script>";
    exit;
}
?>
