<?php
declare(strict_types=1);
require __DIR__.'/app/bootstrap.php';
if(!billing_schema_is_current()){http_response_code(503);exit('Database upgrade required.');}
$cli=PHP_SAPI==='cli';$token=(string)(settings()['cron_token']??'');$authorization=(string)($_SERVER['HTTP_AUTHORIZATION']??'');$presented=str_starts_with($authorization,'Bearer ')?substr($authorization,7):(string)($_GET['token']??'');if(!$cli&&($token===''||!hash_equals($token,$presented))){http_response_code(403);exit('Invalid maintenance token.');}
set_time_limit(180);$notes=[];
try{
    db()->exec('UPDATE documents SET status="overdue" WHERE type="invoice" AND status="sent" AND due_date<CURDATE()');
    if((int)(settings()['auto_reminders']??0)===1){
        $before=max(0,(int)(settings()['reminder_days_before']??2));$overdue=max(1,(int)(settings()['reminder_days_overdue']??3));$balanceSql=finance_document_balance_sql('d');$stmt=db()->prepare('SELECT d.id FROM documents d JOIN customers c ON c.id=d.customer_id WHERE d.type="invoice" AND d.status NOT IN ("draft","cancelled","paid") AND (d.due_date=DATE_ADD(CURDATE(),INTERVAL ? DAY) OR d.due_date=DATE_SUB(CURDATE(),INTERVAL ? DAY)) AND COALESCE(NULLIF(c.whatsapp,""),NULLIF(c.phone,"")) IS NOT NULL AND '.$balanceSql.'>.009 AND NOT EXISTS (SELECT 1 FROM reminder_log rl WHERE rl.document_id=d.id AND DATE(rl.created_at)=CURDATE())');$stmt->execute([$before,$overdue]);$queued=0;foreach($stmt->fetchAll(PDO::FETCH_COLUMN) as $invoiceId){queue_invoice_reminder((int)$invoiceId,'whatsapp',null);$queued++;}$notes[]=$queued.' reminders queued';
        $template=trim((string)(settings()['reminder_template_name']??''));if($template!==''&&whatsapp_is_configured()){$send=db()->query('SELECT r.*,d.number,d.currency_code,'.finance_document_balance_sql('d').' balance FROM reminder_log r JOIN documents d ON d.id=r.document_id WHERE r.status="queued" AND r.channel="whatsapp" AND r.scheduled_for<=NOW() ORDER BY r.id LIMIT 50');$sent=0;foreach($send as $reminder){try{$conversation=whatsapp_conversation((string)$reminder['recipient']);whatsapp_send((int)$conversation['id'],'',null,$template,'en_US',[$reminder['number'],money($reminder['balance'],$reminder['currency_code'])]);db()->prepare('UPDATE reminder_log SET status="sent",sent_at=NOW() WHERE id=?')->execute([$reminder['id']]);$sent++;}catch(Throwable $error){db()->prepare('UPDATE reminder_log SET status="failed",error_message=? WHERE id=?')->execute([substr($error->getMessage(),0,500),$reminder['id']]);}}$notes[]=$sent.' WhatsApp reminders sent';}
    }
    $last=settings()['last_backup_at']??null;if(!$last||strtotime((string)$last)<time()-20*3600){$directory=__DIR__.'/storage/backups';if(!is_dir($directory)&&!mkdir($directory,0750,true)&&!is_dir($directory))throw new RuntimeException('Backup folder could not be created.');$filename='sodazw-auto-'.date('Y-m-d-His').'.sql.gz';$contents=gzencode(sql_backup_contents(),9);if($contents===false||file_put_contents($directory.'/'.$filename,$contents,LOCK_EX)===false)throw new RuntimeException('Scheduled backup could not be written.');db()->prepare('INSERT INTO backup_events (backup_type,filename,file_size,status,notes) VALUES ("scheduled",?,?,"completed","Created by daily maintenance")')->execute([$filename,strlen($contents)]);db()->exec('UPDATE settings SET last_backup_at=NOW() WHERE id=1');foreach(glob($directory.'/sodazw-auto-*.sql.gz')?:[] as $file)if(filemtime($file)<time()-14*86400)unlink($file);$notes[]='scheduled backup completed';}
    audit('daily_maintenance_completed',null,null,implode('; ',$notes));header('Content-Type: text/plain; charset=utf-8');echo 'Soda ZW daily maintenance complete: '.implode('; ',$notes)."\n";
}catch(Throwable $e){try{db()->prepare('INSERT INTO backup_events (backup_type,filename,status,notes) VALUES ("scheduled","maintenance","failed",?)')->execute([substr($e->getMessage(),0,500)]);}catch(Throwable $ignored){}error_log('Soda ZW maintenance: '.$e->getMessage());http_response_code(500);echo 'Maintenance failed. Check the server error log.';}
