<?php
declare(strict_types=1);

require_once __DIR__ . '/_bootstrap.php';

golder_sales_require_post();
$master = golder_master_pdo();
golder_portal_session_start();
$portalUserId = golder_portal_current_user_id();
if ($portalUserId <= 0) {
    golder_json_error(401, 'UNAUTHORIZED', 'Portal login is required.');
}

$portalUser = golder_portal_user_by_id($master, $portalUserId);
if (!$portalUser || trim((string)($portalUser['email_verified_at'] ?? '')) === '') {
    golder_json_error(403, 'FORBIDDEN', 'Portal account is not verified.');
}

golder_sales_rate_limit($master, 'sales_payment_request', 20, 60);
golder_ensure_payment_tables($master);

$payload = golder_sales_payload();
$fullName = trim((string)($payload['full_name'] ?? (string)($portalUser['full_name'] ?? '')));
$email = trim((string)($payload['email'] ?? (string)($portalUser['email'] ?? '')));
$phone = trim((string)($payload['phone'] ?? (string)($portalUser['phone'] ?? '')));
golder_sales_validate_contact($fullName, $email, $phone);

$request = golder_sales_validate_plan_request($payload);
$normalized = $request['normalized'];
$rule = golder_find_pricing_rule($master, (string)$normalized['plan_type'], 'yearly', true);
if (!$rule) {
    golder_json_error(404, 'NOT_FOUND', 'Pricing rule not found.');
}

$pricing = golder_calculate_price($rule, $normalized);
$calculatedAmount = (float)$pricing['total'];
$submittedAmount = (float)($payload['amount'] ?? $calculatedAmount);
$amountDelta = round($submittedAmount - $calculatedAmount, 2);
$mismatchFlag = (abs($amountDelta) > 0.009) ? 1 : 0;

$iban = $master->query('SELECT id, account_name, iban FROM bank_accounts WHERE is_active = 1 ORDER BY display_order ASC, id ASC LIMIT 1')->fetch();
if (!$iban) {
    golder_json_error(404, 'NOT_FOUND', 'No active bank account found.');
}

$paymentCode = golder_generate_payment_code($master);
$requestId = golder_uuid4();
$ins = $master->prepare(
    'INSERT INTO payment_requests
     (id, payment_code, customer_id, portal_user_id, full_name, email, phone, requested_plan_type, requested_pc_devices, requested_web_sessions, duration_key, amount, submitted_amount, calculated_amount, amount_delta, amount_mismatch_flag, currency, iban_id, status, created_at)
     VALUES
     (:id, :pc, NULL, :puid, :fn, :em, :ph, :pt, :pd, :ws, :du, :am, :sam, :cam, :delta, :mm, :cu, :iban, :st, UTC_TIMESTAMP())'
);
$ins->execute([
    ':id' => $requestId,
    ':pc' => $paymentCode,
    ':puid' => $portalUserId,
    ':fn' => $fullName,
    ':em' => ($email !== '' ? $email : null),
    ':ph' => ($phone !== '' ? $phone : null),
    ':pt' => $normalized['plan_type'],
    ':pd' => $normalized['max_pc_devices'],
    ':ws' => $normalized['max_web_sessions'],
    ':du' => 'yearly',
    ':am' => number_format($submittedAmount, 2, '.', ''),
    ':sam' => number_format($submittedAmount, 2, '.', ''),
    ':cam' => number_format($calculatedAmount, 2, '.', ''),
    ':delta' => number_format($amountDelta, 2, '.', ''),
    ':mm' => $mismatchFlag,
    ':cu' => (string)$pricing['currency'],
    ':iban' => (int)($iban['id'] ?? 0),
    ':st' => 'pending',
]);

golder_json_response([
    'status' => 'ok',
    'payment_request_id' => $requestId,
    'payment_code' => $paymentCode,
    'iban' => $iban,
    'pricing' => [
        'submitted_amount' => number_format($submittedAmount, 2, '.', ''),
        'calculated_amount' => number_format($calculatedAmount, 2, '.', ''),
        'amount_delta' => number_format($amountDelta, 2, '.', ''),
        'amount_mismatch_flag' => $mismatchFlag,
        'currency' => (string)$pricing['currency'],
    ],
]);


