<?php
ob_clean(); // Clear any previous output
header('Content-Type: application/json'); // Force JSON format
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include('../include/auth.php');
include('../include/lskfjwfe.php');

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $acriss = trim($_POST['rate_acriss']);
    $max_days = intval($_POST['max_days']);

    // Get all season IDs from the database
    $season_query = "SELECT api_ext_season_id FROM api_ext_seasons";
    $season_result = mysqli_query($db2, $season_query);
    
    $seasons = [];
    while ($row = mysqli_fetch_assoc($season_result)) {
        $seasons[] = $row['api_ext_season_id'];
    }

    // Database transaction for safety
    mysqli_begin_transaction($db2);
    
    try {
        foreach ($seasons as $season_id) {
            for ($i = 1; $i <= 7; $i++) {
                $day_rate = floatval($_POST["season_{$season_id}_day_$i"]);
                $sql = "INSERT INTO api_ext_rates (api_ext_rate_day, api_ext_rate_acriss, api_ext_rate_price, api_ext_rate_seasid)
                        VALUES (?, ?, ?, ?)";
                $stmt = $db2->prepare($sql);
                $stmt->bind_param("isdi", $i, $acriss, $day_rate, $season_id);
                $stmt->execute();
            }

            // Insert rate for days 8 and beyond
            $day_8_rate = floatval($_POST["season_{$season_id}_day_8_onwards"]);
for ($i = 8; $i <= $max_days; $i++) {
    $calculated_price = $i * $day_8_rate; // Correctly scale the price per day
    $sql = "INSERT INTO api_ext_rates (api_ext_rate_day, api_ext_rate_acriss, api_ext_rate_price, api_ext_rate_seasid)
            VALUES (?, ?, ?, ?)";
    $stmt = $db2->prepare($sql);
    $stmt->bind_param("isdi", $i, $acriss, $calculated_price, $season_id);
    $stmt->execute();
}
        }

        // Commit transaction
        mysqli_commit($db2);

       // Log the action
$action = "Add Rates";
$details = "Added rates for ACRISS: $acriss";
$log_query = "INSERT INTO action_logs (action, details, user, timestamp) VALUES ('$action', '$details', '$user', NOW())";

// Execute the log query
if (!mysqli_query($db2, $log_query)) {
    die(json_encode(["success" => false, "message" => "Log Error: " . mysqli_error($db2)]));
}


        header('Content-Type: application/json'); // Ensure JSON response
echo json_encode(["success" => true]);
exit;
    } catch (Exception $e) {
    mysqli_rollback($db2);
    error_log("Database Error: " . $e->getMessage()); // Logs error to the server logs
    echo json_encode(["success" => false, "message" => "Database error: " . $e->getMessage()]);
}

}
?>
