<?php
session_start();
header("Content-Type: application/json");

require_once "../SystemController/DbConnection.php";
require '../SystemController/CsrfProtection.php';
$csrf = new CsrfProtection();
if(!isset($_SESSION['id']) && !isset($_SESSION['loggedid'])){
    header("Location: ../login.php");
}


$db_handle = new Dbconnection();
$csrf = new CsrfProtection();

$new_token = $csrf->generateToken();


if ($_SERVER["REQUEST_METHOD"] === "POST") {
    
    if (!isset($_POST['csrf_token']) || !$csrf->validateToken($_POST['csrf_token'])) {
        die("CSRF token validation failed!");
    }
    $amount   = $db_handle->sanitize($_POST["amount"]) ?? 0;
    $duration = 365;
    $interest_rate = $db_handle->sanitize($_POST["interest_rate"]) ?? "";
    $start_date = $db_handle->sanitize($_POST["start_date"]) ?? "";
    $maturity_date = ($_POST["maturity_date"]) ?? "";
    $estimated_interest = $db_handle->sanitize($_POST["estimated_interest"]);
    $total_at_maturity = $db_handle->sanitize($_POST["total_maturity"]);
    $user_id = $db_handle->sanitize($_POST["id"]);
    
    $status = "ONGOING";
    
    $user = $db_handle->runBaseQuery("SELECT * FROM users WHERE id = $user_id");
    
    $acc_balance = $user[0]['balance'];
    
    if($amount < $acc_balance){
        
        
    $acc_balance -= $amount; 
    $insert = $db_handle->insertRecord("INSERT INTO fixed_deposits(principal,balance,interest_rate,duration_days,start_date,last_interest_date,maturity_date,total_at_maturity,status,user_id) VALUES (?,?,?,?,?,?,?,?,?,?)","sssssssssi",array($amount,$amount,$interest_rate,$duration,$start_date,"",$maturity_date,$total_at_maturity,$status,$user_id));
    
    if($insert){
        
        $db_handle->update("UPDATE users SET fixed_deposit = ?, balance = ? WHERE id = ?","isi",array(1,$acc_balance,$user_id));

    echo json_encode([
        "status" => "success",
        "token" => $new_token,
        "message" => "Fixed deposit of ₦" . number_format($amount) . " for $duration months submitted successfully!"
    ]);
    exit;
}

}else{
    
    echo json_encode([
        "status" => "error",
        "token" => $new_token,
        "message" => "Insufficient Funds, Please fund your account"
    ]);
    exit;
}
}
