<?php
/**
 * ============================================================
 * AJAX: Submit Payment Details
 * ============================================================
 * Submit bKash/Nagad payment details for an existing order
 * Used when user returns to complete payment
 */

// Initialize
define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
require_once BASE_PATH . '/app/config/config.php';

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME);
    session_start();
}

// Must be AJAX POST
if (!isAjax() || !isPost()) {
    Response::error('Invalid request', [], 400);
}

// Validate CSRF
if (!csrf_validate()) {
    Response::csrfError();
}

// Must be logged in
if (!isLoggedIn()) {
    Response::unauthorized();
}

// Load service
require_once APP_PATH . '/services/order_service.php';

// Get POST data
$orderId = (int)post('order_id');
$method = sanitize(post('payment_method'));
$senderMobile = sanitize(post('sender_mobile'));
$trxId = sanitize(post('trx_id'));

// Validate
$validator = Validator::make($_POST);
$validator->required('order_id', 'অর্ডার')
          ->required('payment_method', 'পেমেন্ট মেথড')
          ->in('payment_method', ['bKash', 'Nagad'], 'পেমেন্ট মেথড')
          ->required('sender_mobile', 'প্রেরকের মোবাইল নম্বর')
          ->phone('sender_mobile', 'প্রেরকের মোবাইল নম্বর')
          ->required('trx_id', 'Transaction ID')
          ->minLength('trx_id', 6, 'Transaction ID');

if ($validator->fails()) {
    Response::validationError($validator->errors());
}

// Verify order belongs to user
$order = Database::fetchOne(
    "SELECT id, order_no, grand_total, user_id, payment_status FROM orders WHERE id = ?",
    [$orderId]
);

if (!$order) {
    Response::notFound('অর্ডার পাওয়া যায়নি');
}

if ($order['user_id'] != getUserId()) {
    Response::forbidden('এই অর্ডার আপনার নয়');
}

if ($order['payment_status'] === 'Verified') {
    Response::error('এই অর্ডারের পেমেন্ট ইতিমধ্যে ভেরিফাই হয়েছে');
}

// Submit payment
$result = OrderService::submitPayment(
    $orderId,
    $method,
    $senderMobile,
    $trxId,
    $order['grand_total']
);

if ($result['success']) {
    Response::success($result['message'], [
        'order_id' => $orderId,
        'order_no' => $order['order_no']
    ]);
} else {
    Response::error($result['message']);
}
