<?php

if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    exit("Forbidden");
}
require_once __DIR__ ."/../SystemController/DbConnection.php";
$db_handle = new DbConnection();

$plans = $db_handle->runBaseQuery("SELECT * FROM savings_plans 
        WHERE status = 'ONGOING' AND end_date <= CURDATE()");



if (!$plans) {
    die("Error fetching plans: ");
}

$completedPlans = 0;

foreach($plans as $plan) {
    $plan_id = $plan['id'];
    $user_id = $plan['userID'];
    
    $status = "COMPLETED";

    $update = $db_handle->update("UPDATE savings_plans SET status = ?
               WHERE id = ?","si",array($status,$plan_id));

    if ($update) {
        
        $user = $db_handle->runBaseQuery("SELECT * FROM users WHERE id = $user_id");
        
        $balance = $user[0]['balance'];
        
        $savings = $db_handle->runBaseQuery("SELECT sum(amount) as saved FROM savings WHERE userID = $user_id AND planID = $plan_id AND status = 'SUCCESSFUL'");
        
        $total = $savings[0]['saved'];
        $balance += $total;
        
        $upd = $db_handle->update("UPDATE users SET balance = ? WHERE id = ?","si",array($balance,$user_id));
        
        if($upd){
            
        $completedPlans++;    
        }
        
    }
}

echo "$completedPlans plan(s) marked as completed.";

?>
