<?php
error_reporting(E_ALL);
ini_set('display_errors', 0); // hide HTML errors
ini_set('log_errors', 1);
ini_set('error_log', __DIR__.'/error.log');

require __DIR__ . '/../config.php';
header('Content-Type: application/json');

function jsonError($msg, $code=400) {
    http_response_code($code);
    echo json_encode(['success'=>false, 'error'=>$msg]);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);

$orderId   = $data['orderID'] ?? '';
$invoiceId = (int)($data['invoice_id'] ?? 0);
$uuid      = $data['uuid'] ?? '';
$hash      = $data['hash'] ?? '';

if(!$orderId || !$invoiceId || !$uuid || !$hash){
    jsonError("Invalid request");
}

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($conn->connect_error) jsonError("DB connection failed", 500);

// VERIFY INVOICE
$stmt = $conn->prepare("SELECT salt, payment_method_id FROM invoices WHERE id=? AND uuid=? AND status!='paid'");
$stmt->bind_param("is",$invoiceId,$uuid);
$stmt->execute();
$invoice = $stmt->get_result()->fetch_assoc();
$stmt->close();

if(!$invoice || !hash_equals(generateInvoiceHash($invoiceId, $invoice['salt']), $hash)){
    jsonError("Invalid invoice", 403);
}

// FETCH PAYPAL KEYS
$pmId = (int)$invoice['payment_method_id'];
$pmStmt = $conn->prepare("SELECT * FROM payment_methods WHERE id=? AND status=1");
$pmStmt->bind_param("i", $pmId);
$pmStmt->execute();
$gateway = $pmStmt->get_result()->fetch_assoc();
$pmStmt->close();

if(!$gateway){
    jsonError("Payment method missing");
}

// define('PAYPAL_CLIENT_ID',  $gateway['paypal_client_id']);
// define('PAYPAL_SECRET',     $gateway['paypal_secret_key']);

 $live_client_id =  $gateway['paypal_client_id'];
 $live_secret_key = $gateway['paypal_secret_key'];


        // SANDBOX KEYS
    $sandbox_client_id     = "AWC6zxQassGuh4XAdXlEQoqEBsAOfz5Lnl9RH8ChUW9kwCDBPbtrAcQtnTADgJU2dx_WcPWqHoeBeI43";
    $sandbox_secret_key    = "EEvaaFagj2_cSfQE7wXju0hANng0_PJQ9mAe9dmlJqzgNTm3OmOmtVun6JYfCn_jEorSxnh3XmKI2JC1";
    

    
    // Define PayPal credentials dynamically based on mode
    define('PAYPAL_CLIENT_ID', PAYPAL_MODE === 'sandbox' ? $sandbox_client_id : $live_client_id);
    define('PAYPAL_SECRET', PAYPAL_MODE === 'sandbox' ? $sandbox_secret_key : $live_secret_key);


// GET ACCESS TOKEN
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, PAYPAL_API."/v1/oauth2/token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, PAYPAL_CLIENT_ID.":".PAYPAL_SECRET);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
$res = curl_exec($ch);
$tokenData = json_decode($res,true);
$accessToken = $tokenData['access_token'] ?? '';
curl_close($ch);

if(!$accessToken){
    jsonError("Token error", 500);
}

// CAPTURE ORDER
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, PAYPAL_API."/v2/checkout/orders/".$orderId."/capture");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Authorization: Bearer $accessToken"
]);
$res = curl_exec($ch);
curl_close($ch);

$capture = json_decode($res,true);
$capId = $capture['purchase_units'][0]['payments']['captures'][0]['id'] ?? null;

if(!$capId){
    jsonError("Capture failed");
}

// UPDATE INVOICE
$stmt = $conn->prepare("UPDATE invoices SET status='paid', paid_at=NOW(), paypal_transaction_id=? WHERE id=?");
$stmt->bind_param("si",$capId,$invoiceId);
$stmt->execute();
$stmt->close();
$conn->close();

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