<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include '../connection.php';




$order_id = intval($_POST['order_id'] ?? 0);
$amount   = floatval($_POST['amount'] ?? 0);
$method   = $_POST['method'] ?? 'cod';

if (!$order_id || !$amount) exit(json_encode(['success'=>false,'msg'=>'Bad params']));

// record INIT in tbl_payment_transactions
$tran_id = $tran_id = 'wavoo_' . date('YmdHis') . '_' . mt_rand(1000, 9999);   // your own reference
$stmt = $conn->prepare("INSERT INTO tbl_payment_transactions 
        (order_id,gateway,tran_id,amount,status) VALUES (?,?,?,?, 'INIT')");
$stmt->bind_param('isds', $order_id, $method, $tran_id, $amount);
$stmt->execute();

switch ($method) {
/* -------------------------------------------------------- *
 * 1) CASH‑ON‑DELIVERY – no external call
 * -------------------------------------------------------- */
case 'cod':
    // mark order + transaction as SUCCESS immediately
    $conn->query("UPDATE tbl_order SET status ='Completed', payment_status='COD Confirmed' WHERE id=$order_id");
    $conn->query("UPDATE tbl_payment_transactions 
                  SET status='SUCCESS' WHERE tran_id='$tran_id'");
    echo json_encode(['success'=>true, 'cod'=>true]);
    exit;

/* -------------------------------------------------------- *
 * 2) SSLCOMMERZ – EasyCheckout (latest v4 API)            *
 * -------------------------------------------------------- */
case 'sslcommerz':
    // *** read your store credentials from env or constants ***
    $store_id  = 'your_store_id';
    $store_pass= 'your_store_passwd';

    $post_data = [
        'store_id'       => $store_id,
        'store_passwd'   => $store_pass,
        'total_amount'   => number_format($amount,2,'.',''),
        'currency'       => 'XOF',
        'tran_id'        => $tran_id,
        'success_url'    => 'https://your‑domain.com/api/payment/ssl_ipn.php',
        'fail_url'       => 'https://your‑domain.com/api/payment/ssl_ipn.php',
        'cancel_url'     => 'https://your‑domain.com/api/payment/ssl_ipn.php',
        'cus_name'       => 'Wavoo User',
        'cus_email'      => 'client@example.com',
        'cus_add1'       => 'Dhaka',
        'cus_phone'      => '8801XXXXXXXXX',
        // … more optional fields …
    ];

    $handle = curl_init('https://securepay.sslcommerz.com/gwprocess/v4/api.php');
    curl_setopt($handle, CURLOPT_TIMEOUT, 30);
    curl_setopt($handle, CURLOPT_POST, 1);
    curl_setopt($handle, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    $content = curl_exec($handle);
    curl_close($handle);

    $response = json_decode($content, true);
    if (isset($response['GatewayPageURL']) && $response['GatewayPageURL']!='') {
        echo json_encode(['success'=>true,
                          'pay_url'=>$response['GatewayPageURL'],
                          'tran_id'=>$tran_id]);
    } else {
        $conn->query("UPDATE tbl_payment_transactions 
                      SET status='FAILED' WHERE tran_id='$tran_id'");
        echo json_encode(['success'=>false,'msg'=>'SSL init failed']);
    }
    exit;

/* -------------------------------------------------------- *
 * 3) STRIPE – create Checkout Session (simple)
 * -------------------------------------------------------- */
case 'stripe':
    require_once 'vendor/autoload.php';       // composer require stripe/stripe-php
    \Stripe\Stripe::setApiKey('sk_live_…');

    $session = \Stripe\Checkout\Session::create([
        'mode'            => 'payment',
        'success_url'     => 'https://your‑domain.com/payment_success.html',
        'cancel_url'      => 'https://your‑domain.com/payment_cancel.html',
        'line_items'      => [[
            'price_data'=>[
                'currency'=>'xof',
                'product_data'=>['name'=>"Wavoo Order #$order_id"],
                'unit_amount'=> $amount*100,      // Stripe expects cents
            ],
            'quantity'=>1,
        ]],
        'metadata'=>[
            'order_id'=>$order_id,
            'tran_id' =>$tran_id,
        ],
    ]);
    echo json_encode(['success'=>true, 'pay_url'=>$session->url]);
    exit;
default:
    echo json_encode(['success'=>false,'msg'=>'Unsupported gateway']);
}

?>
