<?php
// Prevent direct web access
if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    exit("Forbidden");
}
/*error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

file_put_contents(__DIR__ . "/cron_debug.log", "Cron ran at " . date("Y-m-d H:i:s") . "\n", FILE_APPEND);*/



require_once __DIR__ ."/../SystemController/DbConnection.php";
$db_handle = new DbConnection();
$today = date("Y-m-d");


$deposits = $db_handle->runBaseQuery("
    SELECT * FROM fixed_deposits
    WHERE DATE(start_date) <= '$today'
    AND DATE_ADD(DATE(start_date), INTERVAL duration_days DAY) >= '$today'
");

/*$deposits = $db_handle->runBaseQuery("SELECT * FROM fixed_deposits 
          WHERE DATE_ADD(start_date, INTERVAL duration_days DAY) >= '$today'");*/
          
          if($deposits){

foreach ($deposits as $deposit) {
    
    if ($deposit['last_interest_date'] === $today || $deposit['start_date'] === $today) {
        continue;
    }
    $deposit_id = $deposit['id'];
    $user_id = $deposit['user_id'];
    $balance = $deposit['balance'];
    $rate = $deposit['interest_rate']; 

    
    $dailyRate = ($rate / 100) / 365;
  $interest = $balance * $dailyRate;

    $newBalance = $balance + $interest;

    
  $update = $db_handle->update(
        "UPDATE fixed_deposits SET balance = ?, last_interest_date = ? WHERE id = ?","dsi", array($newBalance, $today, $deposit['id']));
        
        
        if ($maturityDate === $today) {
            
            $user = $db_handle->runBaseQuery("SELECT balance FROM users WHERE id = $user_id");
            if ($user) {
                $userBalance = (float)$user[0]['balance'];
                 
                $newUserBalance = round($userBalance + $newBalance, 2);

               
$db_handle->update("UPDATE users SET balance = ? WHERE id = ?","di",array($newUserBalance, $user_id));

                
        $db_handle->update("UPDATE fixed_deposits SET status = ? WHERE id = ?", "si",array("COMPLETED", $deposit_id));
            }
        }
}
}

?>