<?php
require_once __DIR__.'/../app/bootstrap.php';
use App\Core\Auth;use App\Core\Database;use App\Core\Response;
if($_SERVER['REQUEST_METHOD']!=='POST'||!verify_csrf())Response::json(['ok'=>false,'message'=>'Invalid request.'],419);
$d=request_data();$code=strtoupper(trim((string)($d['code']??'')));$subtotal=max(0,(float)($d['subtotal']??0));
$c=Database::safeFetchOne('SELECT * FROM coupons WHERE UPPER(code)=? AND status="active" AND (starts_at IS NULL OR starts_at<=NOW()) AND (ends_at IS NULL OR ends_at>=NOW()) LIMIT 1',[$code]);
if(!$c)Response::json(['ok'=>false,'message'=>'Coupon is invalid or expired.'],422);
if($subtotal<(float)($c['min_order_amount']??0))Response::json(['ok'=>false,'message'=>'Minimum order amount is '.money($c['min_order_amount']).'.'],422);
if(!empty($c['usage_limit'])&&db_count('coupon_usages','coupon_id=?',[(int)$c['id']])>=(int)$c['usage_limit'])Response::json(['ok'=>false,'message'=>'Coupon usage limit has been reached.'],422);
$discount=$c['discount_type']==='percentage'?round($subtotal*((float)$c['discount_value']/100),2):(float)$c['discount_value'];$discount=min($subtotal,max(0,$discount));
Response::json(['ok'=>true,'coupon_id'=>(int)$c['id'],'code'=>$c['code'],'discount'=>$discount,'formatted_discount'=>money($discount),'total'=>round($subtotal-$discount,2)]);
