<?php
date_default_timezone_set("Africa/Lagos");
require_once '../../vendor/autoload.php';
require_once '../../include/DatabaseConn.php';
require_once '../../include/Constants.php';
require_once '../../models/Invoice.php';

$db = new DatabaseConn();
$link = $db->connect();

$std = new stdClass();

$id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
$email = filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL);
$capital = filter_input(INPUT_GET, "capital", FILTER_VALIDATE_FLOAT);
$profit = filter_input(INPUT_GET, "profit", FILTER_VALIDATE_FLOAT);
$days = filter_input(INPUT_GET, "days", FILTER_VALIDATE_INT);
$plan = filter_input(INPUT_GET, "plan", FILTER_SANITIZE_STRING);


header("content-type: application/json");

if (is_null($id)) {
    $error = 'Token missing in request body';
    $std->error = $error;
    echo (json_encode($std));
    die();
} else if (is_null($email)) {
    $error = 'Token missing in request body';
    $std->error = $error;
    echo (json_encode($std));
    die();
} else if (is_null($capital)) {
    $error = 'Enter a valid capital';
    $std->error = $error;
    echo (json_encode($std));
    die();
} else if (is_null($profit)) {
    $error = 'Enter a valid profit';
    $std->error = $error;
    echo (json_encode($std));
    die();
}else if (is_null($days)) {
    $error = 'Enter a valid day count';
    $std->error = $error;
    echo (json_encode($std));
    die();
} else {
    $status = GROWING;
    $time = time();
   
    // 3. Fetch Current Invoice Data
    $selectQuery = "SELECT amount, cReturns FROM invoice WHERE id = ? AND `user` = ?";
    if ($stmtSelect = $link->prepare($selectQuery)) {
        $stmtSelect->bind_param("is", $id, $email);
        $stmtSelect->execute();
        $stmtSelect->bind_result($currentAmount, $currentCReturns);
        
        if ($stmtSelect->fetch()) {
            // Data fetched successfully
        } else {
            die("No invoice found with the provided ID and user.");
        }
        $stmtSelect->close();
    } 
       $insertQuery = "INSERT INTO edits (`total`, `net`, `user`, `date`) VALUES (?, ?, ?, ?)";
    if ($stmtInsert = $link->prepare($insertQuery)) {
        $stmtInsert->bind_param("ddss", $currentAmount, $currentCReturns, $email, $time);
        if (!$stmtInsert->execute()) {
            die("Execute failed: (" . $stmtInsert->errno . ") " . $stmtInsert->error);
        }
        $stmtInsert->close();
    }
    mysqli_query($link, "update invoice set amount = $capital, `cReturns` = $profit, `count` = $days, `package` = '$plan'  WHERE id = $id and `user` = '$email' ");
    if (mysqli_affected_rows($link) == 1) {
        $std->msg = PAID;
        $time = time();
        
        echo (json_encode($std));
        die();
    } else {
        $error = 'Already updated';
        $std->error = $error;
        echo (json_encode($std));
        die();
    }
}

