<?php

declare(strict_types=1);

session_start();

require_once '../config.php';



header('Content-Type: application/json');



$is_setup = !empty($_SESSION['setup_auth']);



if (!$is_setup) {

    requireModule('online_payments', true);

    if (!isset($_SESSION['user_id'])) {

        echo json_encode(['success' => false, 'message' => 'Unauthorized']);

        exit;

    }

    if (!in_array($_SESSION['role'] ?? '', ['admin', 'headteacher'], true)) {

        echo json_encode(['success' => false, 'message' => 'Access denied']);

        exit;

    }

}



$conn   = getDBConnection();

$action = trim((string) ($_POST['action'] ?? ''));



function ps_saveSetting(mysqli $conn, string $key, string $value): void

{

    $stmt = $conn->prepare(

        "INSERT INTO settings (setting_key, setting_value) VALUES (?, ?)

         ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)"

    );

    $stmt->bind_param('ss', $key, $value);

    $stmt->execute();

    $stmt->close();

}



function ps_getSecretKey(): string

{

    global $config, $is_setup;

    // During setup the DB may not be accessible yet; accept key passed directly from the form

    if ($is_setup && !empty($_POST['paystack_key'])) {

        return trim((string) $_POST['paystack_key']);

    }

    $key = getSettingValue('paystack_secret_key') ?: ($config['paystack']['secret_key'] ?? '');

    return trim((string) $key);

}



switch ($action) {



    // ── LIST BANKS ────────────────────────────────────────────────────────────

    case 'get_banks':

        $cacheDir  = __DIR__ . '/../cache';

        $cacheFile = $cacheDir . '/paystack_banks.json';



        if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < 86400) {

            $cached = json_decode((string) file_get_contents($cacheFile), true);

            if (!empty($cached['banks'])) {

                echo json_encode(['success' => true, 'banks' => $cached['banks']]);

                exit;

            }

        }



        $secretKey = ps_getSecretKey();

        if ($secretKey === '') {

            echo json_encode(['success' => false, 'message' => 'Paystack secret key not configured. Add it in Settings → Payment Gateway first.']);

            exit;

        }



        $ch = curl_init('https://api.paystack.co/bank?country=ghana&currency=GHS&use_cursor=false&perPage=100');

        curl_setopt_array($ch, [

            CURLOPT_RETURNTRANSFER => true,

            CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . $secretKey],

            CURLOPT_SSL_VERIFYPEER => true,

            CURLOPT_TIMEOUT        => 15,

        ]);

        $response = curl_exec($ch);

        $httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);



        $decoded = json_decode($response ?: '{}', true);

        if ($httpCode === 200 && !empty($decoded['data'])) {

            $banks = array_map(

                static fn(array $b): array => ['name' => $b['name'], 'code' => $b['code']],

                $decoded['data']

            );

            if (!is_dir($cacheDir)) {

                mkdir($cacheDir, 0755, true);

            }

            file_put_contents($cacheFile, json_encode(['banks' => $banks, 'cached_at' => date('c')]));

            echo json_encode(['success' => true, 'banks' => $banks]);

        } else {

            $msg = $decoded['message'] ?? 'Failed to load banks from Paystack.';

            error_log("Paystack get_banks error: HTTP {$httpCode} — {$msg}");

            echo json_encode(['success' => false, 'message' => $msg]);

        }

        break;



    // ── VERIFY ACCOUNT ────────────────────────────────────────────────────────

    case 'verify_account':

        $accountNumber = trim((string) ($_POST['account_number'] ?? ''));

        $bankCode      = trim((string) ($_POST['bank_code'] ?? ''));



        if ($accountNumber === '' || $bankCode === '') {

            echo json_encode(['success' => false, 'message' => 'Account number and bank code are required.']);

            exit;

        }



        $secretKey = ps_getSecretKey();

        if ($secretKey === '') {

            echo json_encode(['success' => false, 'message' => 'Paystack secret key not configured.']);

            exit;

        }



        $url = 'https://api.paystack.co/bank/resolve?account_number='

             . urlencode($accountNumber) . '&bank_code=' . urlencode($bankCode);

        $ch = curl_init($url);

        curl_setopt_array($ch, [

            CURLOPT_RETURNTRANSFER => true,

            CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . $secretKey],

            CURLOPT_SSL_VERIFYPEER => true,

            CURLOPT_TIMEOUT        => 15,

        ]);

        $response = curl_exec($ch);

        $httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);



        $decoded = json_decode($response ?: '{}', true);

        if ($httpCode === 200 && !empty($decoded['data']['account_name'])) {

            echo json_encode(['success' => true, 'account_name' => $decoded['data']['account_name']]);

        } else {

            $msg = $decoded['message'] ?? 'Could not verify account. Check account number and bank selection.';

            echo json_encode(['success' => false, 'message' => $msg]);

        }

        break;



    // ── CREATE SUBACCOUNT ─────────────────────────────────────────────────────

    case 'create_subaccount':

        $businessName     = trim((string) ($_POST['business_name'] ?? ''));

        $settlementBank   = trim((string) ($_POST['settlement_bank'] ?? ''));

        $accountNumber    = trim((string) ($_POST['account_number'] ?? ''));

        $bankName         = trim((string) ($_POST['bank_name'] ?? ''));

        $percentageCharge = max(0.0, (float) ($_POST['percentage_charge'] ?? 0));



        if ($businessName === '' || $settlementBank === '' || $accountNumber === '') {

            echo json_encode(['success' => false, 'message' => 'Business name, bank, and account number are required.']);

            exit;

        }



        $secretKey = ps_getSecretKey();

        if ($secretKey === '') {

            echo json_encode(['success' => false, 'message' => 'Paystack secret key not configured. Add it in Settings → Payment Gateway first.']);

            exit;

        }



        // If a subaccount code already exists, update instead of creating a duplicate

        $existingCode = trim((string) (getSettingValue('paystack_subaccount_code') ?? ''));

        if ($existingCode !== '') {

            $updatePayload = array_filter([

                'business_name'   => $businessName ?: null,

                'settlement_bank' => $settlementBank ?: null,

                'account_number'  => $accountNumber ?: null,

            ]);

            $ch = curl_init('https://api.paystack.co/subaccount/' . urlencode($existingCode));

            curl_setopt_array($ch, [

                CURLOPT_CUSTOMREQUEST  => 'PUT',

                CURLOPT_POSTFIELDS     => json_encode($updatePayload),

                CURLOPT_RETURNTRANSFER => true,

                CURLOPT_HTTPHEADER     => [

                    'Authorization: Bearer ' . $secretKey,

                    'Content-Type: application/json',

                ],

                CURLOPT_SSL_VERIFYPEER => true,

                CURLOPT_TIMEOUT        => 20,

            ]);

            $response = curl_exec($ch);

            $httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);

            curl_close($ch);



            $decoded = json_decode($response ?: '{}', true);

            if ($httpCode === 200 && !empty($decoded['status'])) {

                if ($bankName)      ps_saveSetting($conn, 'school_bank_name', $bankName);

                if ($accountNumber) ps_saveSetting($conn, 'school_bank_account_number', $accountNumber);

                if ($businessName)  ps_saveSetting($conn, 'school_bank_account_name', $businessName);

                ps_saveSetting($conn, 'school_bank_code', $settlementBank);

                echo json_encode(['success' => true, 'subaccount_code' => $existingCode, 'message' => 'Settlement account updated successfully.']);

            } else {

                $msg = $decoded['message'] ?? 'Failed to update Paystack subaccount.';

                error_log("Paystack update_subaccount (via create) error: HTTP {$httpCode} — {$msg}");

                echo json_encode(['success' => false, 'message' => $msg]);

            }

            break;

        }



        $payload = [

            'business_name'         => $businessName,

            'settlement_bank'       => $settlementBank,

            'account_number'        => $accountNumber,

            'percentage_charge'     => $percentageCharge,

            'primary_contact_email' => (string) (getSettingValue('school_email') ?: ''),

            'primary_contact_name'  => $businessName,

            'primary_contact_phone' => (string) (getSettingValue('school_phone') ?: ''),

        ];



        $ch = curl_init('https://api.paystack.co/subaccount');

        curl_setopt_array($ch, [

            CURLOPT_POST           => true,

            CURLOPT_POSTFIELDS     => json_encode($payload),

            CURLOPT_RETURNTRANSFER => true,

            CURLOPT_HTTPHEADER     => [

                'Authorization: Bearer ' . $secretKey,

                'Content-Type: application/json',

            ],

            CURLOPT_SSL_VERIFYPEER => true,

            CURLOPT_TIMEOUT        => 20,

        ]);

        $response = curl_exec($ch);

        $httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);



        $decoded = json_decode($response ?: '{}', true);

        if (($httpCode === 200 || $httpCode === 201) && !empty($decoded['data']['subaccount_code'])) {

            $subCode = $decoded['data']['subaccount_code'];

            $subId   = (string) ($decoded['data']['id'] ?? '');



            ps_saveSetting($conn, 'paystack_subaccount_code',    $subCode);

            ps_saveSetting($conn, 'paystack_subaccount_id',      $subId);

            ps_saveSetting($conn, 'paystack_split_enabled',      '1');

            ps_saveSetting($conn, 'paystack_bearer',             'account');

            ps_saveSetting($conn, 'school_bank_name',            $bankName);

            ps_saveSetting($conn, 'school_bank_account_number',  $accountNumber);

            ps_saveSetting($conn, 'school_bank_account_name',    $businessName);

            ps_saveSetting($conn, 'school_bank_code',            $settlementBank);



            echo json_encode([

                'success'         => true,

                'subaccount_code' => $subCode,

                'message'         => 'Settlement account configured. Online payments will now go directly to your school bank account.',

            ]);

        } else {

            $msg = $decoded['message'] ?? 'Failed to create Paystack subaccount.';

            error_log("Paystack create_subaccount error: HTTP {$httpCode} — {$msg} | Body: " . $response);

            echo json_encode(['success' => false, 'message' => $msg]);

        }

        break;



    // ── UPDATE SUBACCOUNT ─────────────────────────────────────────────────────

    case 'update_subaccount':

        $subCode       = trim((string) ($_POST['subaccount_code'] ?? getSettingValue('paystack_subaccount_code')));

        $businessName  = trim((string) ($_POST['business_name'] ?? ''));

        $settlementBank = trim((string) ($_POST['settlement_bank'] ?? ''));

        $accountNumber  = trim((string) ($_POST['account_number'] ?? ''));

        $bankName       = trim((string) ($_POST['bank_name'] ?? ''));



        if ($subCode === '') {

            echo json_encode(['success' => false, 'message' => 'No subaccount code found. Create a subaccount first.']);

            exit;

        }



        $secretKey = ps_getSecretKey();

        if ($secretKey === '') {

            echo json_encode(['success' => false, 'message' => 'Paystack secret key not configured.']);

            exit;

        }



        $updatePayload = array_filter([

            'business_name'   => $businessName ?: null,

            'settlement_bank' => $settlementBank ?: null,

            'account_number'  => $accountNumber ?: null,

        ]);



        $ch = curl_init('https://api.paystack.co/subaccount/' . urlencode($subCode));

        curl_setopt_array($ch, [

            CURLOPT_CUSTOMREQUEST  => 'PUT',

            CURLOPT_POSTFIELDS     => json_encode($updatePayload),

            CURLOPT_RETURNTRANSFER => true,

            CURLOPT_HTTPHEADER     => [

                'Authorization: Bearer ' . $secretKey,

                'Content-Type: application/json',

            ],

            CURLOPT_SSL_VERIFYPEER => true,

            CURLOPT_TIMEOUT        => 20,

        ]);

        $response = curl_exec($ch);

        $httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);



        $decoded = json_decode($response ?: '{}', true);

        if ($httpCode === 200 && !empty($decoded['status'])) {

            if ($bankName)       ps_saveSetting($conn, 'school_bank_name', $bankName);

            if ($accountNumber)  ps_saveSetting($conn, 'school_bank_account_number', $accountNumber);

            if ($businessName)   ps_saveSetting($conn, 'school_bank_account_name', $businessName);

            if ($settlementBank) ps_saveSetting($conn, 'school_bank_code', $settlementBank);

            echo json_encode(['success' => true, 'message' => 'Subaccount updated successfully.']);

        } else {

            $msg = $decoded['message'] ?? 'Failed to update subaccount.';

            error_log("Paystack update_subaccount error: HTTP {$httpCode} — {$msg}");

            echo json_encode(['success' => false, 'message' => $msg]);

        }

        break;



    default:

        echo json_encode(['success' => false, 'message' => 'Unknown action.']);

}

