<?php
require_once __DIR__ . '/_bootstrap.php';
use App\Core\Database;

$job='pos_day_close';
$started=date('Y-m-d H:i:s');
$date = PHP_SAPI === 'cli' ? ($argv[1] ?? date('Y-m-d', strtotime('-1 day'))) : (string)($_GET['date'] ?? date('Y-m-d', strtotime('-1 day')));
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/',$date) || !DateTimeImmutable::createFromFormat('!Y-m-d',$date)) {
    cron_log($job,'failed','Invalid business date. Use YYYY-MM-DD.',$started);
    exit(1);
}
try {
    $vendors=Database::fetchAll('SELECT DISTINCT vendor_id FROM pos_sales WHERE DATE(created_at)=?',[$date]);
    $closed=0;
    foreach($vendors as $vendor){
        $vendorId=(int)$vendor['vendor_id'];
        $row=Database::fetchOne('SELECT COALESCE(SUM(subtotal),0) gross,COALESCE(SUM(discount_amount),0) discount_amount,COALESCE(SUM(tax_amount),0) tax_amount,COALESCE(SUM(total_amount),0) net_sales FROM pos_sales WHERE vendor_id=? AND DATE(created_at)=?',[$vendorId,$date]);
        $refund=Database::fetchOne('SELECT COALESCE(SUM(pr.amount),0) refund_amount FROM pos_refunds pr JOIN pos_sales ps ON ps.id=pr.sale_id WHERE ps.vendor_id=? AND pr.status IN ("approved","paid","completed") AND DATE(pr.created_at)=?',[$vendorId,$date]);
        $existing=Database::fetchOne('SELECT id FROM pos_day_closings WHERE vendor_id=? AND business_date=? AND outlet_id IS NULL ORDER BY id DESC LIMIT 1',[$vendorId,$date]);
        $values=[(float)($row['gross']??0),(float)($row['discount_amount']??0),(float)($row['tax_amount']??0),(float)($refund['refund_amount']??0),(float)($row['net_sales']??0)];
        if($existing){
            Database::execute('UPDATE pos_day_closings SET gross_sales=?,discount_amount=?,tax_amount=?,refund_amount=?,net_sales=?,closed_at=NOW(),status="closed" WHERE id=?',[...$values,(int)$existing['id']]);
        }else{
            Database::execute('INSERT INTO pos_day_closings (vendor_id,outlet_id,business_date,gross_sales,discount_amount,tax_amount,refund_amount,net_sales,closed_at,status) VALUES (?,NULL,?,?,?,?,?,?,NOW(),"closed")',[$vendorId,$date,...$values]);
        }
        $closed++;
    }
    cron_log($job,'success','Closed or refreshed '.$closed.' vendor POS day record(s) for '.$date.'.',$started);
}catch(Throwable $e){cron_log($job,'failed',$e->getMessage(),$started);exit(1);}
