<?php
/** Run from Windows Task Scheduler or cron; never expose this script through HTTP. */
if (PHP_SAPI !== 'cli') { http_response_code(403); exit('CLI only'); }
require_once __DIR__ . '/../config/config.php';

$returnsProcessed = 0; $maturitiesProcessed = 0;
$dueReturns = $conn->query("SELECT id FROM investment_return_payments WHERE status='pending' AND due_date<=NOW() ORDER BY due_date,id");
while ($row = $dueReturns->fetch_assoc()) {
    try {
        $conn->begin_transaction(); $id=(int)$row['id'];
        $payment=$conn->prepare("SELECT rp.*,i.status AS investment_status FROM investment_return_payments rp JOIN investments i ON i.id=rp.investment_id WHERE rp.id=? FOR UPDATE");
        $payment->bind_param('i',$id);$payment->execute();$data=$payment->get_result()->fetch_assoc();$payment->close();
        if(!$data || $data['status']!=='pending' || $data['investment_status']!=='active' || strtotime($data['due_date'])>time()){$conn->rollback();continue;}
        $amount=(float)$data['amount'];$userId=(int)$data['user_id'];
        $credit=$conn->prepare('UPDATE users SET account_balance=account_balance+? WHERE id=?');$credit->bind_param('di',$amount,$userId);$credit->execute();$credit->close();
        $mark=$conn->prepare("UPDATE investment_return_payments SET status='paid',paid_at=NOW() WHERE id=?");$mark->bind_param('i',$id);$mark->execute();$mark->close();
        $description='Return payment '.$data['period_number'].' of investment #'.$data['investment_id'].': £'.number_format($amount,2).' ('.$data['rate_percent'].'% of your principal) credited.';
        $earning=$conn->prepare('INSERT INTO earnings (user_id,amount,description) VALUES (?,?,?)');$earning->bind_param('ids',$userId,$amount,$description);$earning->execute();$earning->close();
        $reference='RET-'.$id.'-'.date('YmdHis');$ledger=$conn->prepare("INSERT INTO transactions (user_id,reference,transaction_type,direction,amount,currency,status,description,source_table,source_id) VALUES (?,?,'earning','credit',?,'GBP','completed',?,'investment_return_payments',?)");$ledger->bind_param('isdsi',$userId,$reference,$amount,$description,$id);$ledger->execute();$ledger->close();
        $log=$conn->prepare("INSERT INTO activity_logs (user_id,actor,action_type,description) VALUES (?,'system','investment_return',?)");$log->bind_param('is',$userId,$description);$log->execute();$log->close();$conn->commit();$returnsProcessed++;
    } catch(Throwable $e){$conn->rollback();fwrite(STDERR,"Return payment failed: {$e->getMessage()}\n");}
}

$matured=$conn->query("SELECT id FROM investments WHERE status='active' AND end_date<=NOW() ORDER BY id");
while($row=$matured->fetch_assoc()){
    try{
        $conn->begin_transaction();$investmentId=(int)$row['id'];$investment=$conn->prepare("SELECT * FROM investments WHERE id=? AND status='active' FOR UPDATE");$investment->bind_param('i',$investmentId);$investment->execute();$data=$investment->get_result()->fetch_assoc();$investment->close();
        if(!$data||strtotime($data['end_date'])>time()){$conn->rollback();continue;}
        $principal=(float)$data['amount'];$count=$conn->prepare('SELECT COUNT(*) AS count FROM investment_return_payments WHERE investment_id=?');$count->bind_param('i',$investmentId);$count->execute();$hasSchedule=(int)$count->get_result()->fetch_assoc()['count']>0;$count->close();
        $credited=$hasSchedule?$principal:(float)$data['expected_return'];$return=round($credited-$principal,2);
        $payout=$conn->prepare("INSERT INTO investment_payouts (investment_id,user_id,principal_amount,return_amount,credited_amount,processed_at) VALUES (?,?,?,?,?,NOW())");$payout->bind_param('iiddd',$investmentId,$data['user_id'],$principal,$return,$credited);if(!$payout->execute()){$payout->close();$conn->rollback();continue;}$payout->close();
        $user=$conn->prepare('UPDATE users SET account_balance=account_balance+? WHERE id=?');$user->bind_param('di',$credited,$data['user_id']);$user->execute();$user->close();$complete=$conn->prepare("UPDATE investments SET status='completed' WHERE id=?");$complete->bind_param('i',$investmentId);$complete->execute();$complete->close();
        $description='Investment #'.$investmentId.' matured. Principal of £'.number_format($credited,2).' credited to your available balance.';$reference='MAT-'.$investmentId.'-'.date('YmdHis');$ledger=$conn->prepare("INSERT INTO transactions (user_id,reference,transaction_type,direction,amount,currency,status,description,source_table,source_id) VALUES (?,?,'earning','credit',?,'GBP','completed',?,'investments',?)");$ledger->bind_param('isdsi',$data['user_id'],$reference,$credited,$description,$investmentId);$ledger->execute();$ledger->close();$log=$conn->prepare("INSERT INTO activity_logs (user_id,actor,action_type,description) VALUES (?,'system','investment_maturity',?)");$log->bind_param('is',$data['user_id'],$description);$log->execute();$log->close();$conn->commit();$maturitiesProcessed++;
    }catch(Throwable $e){$conn->rollback();fwrite(STDERR,"Investment maturity failed: {$e->getMessage()}\n");}
}
echo "Processed {$returnsProcessed} return payment(s) and {$maturitiesProcessed} maturity payout(s).\n";