<?php
// update_amount.php - Tool for batch updating partnership commitment amounts
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Include database connection (must define $conn object)
include 'db_connect.php'; 

// --- 1. Define Commitment Amount Mapping ---
$commitment_map = [
    1 => 20000.00,
    2 => 50000.00,
    3 => 200000.00, // Stored as decimal/float
    4 => 500000.00,
    5 => 700000.00,
    6 => 1000000.00,
];

// --- 2. PHP Batch Update Logic (Executed via AJAX) ---
if (isset($_GET['action']) && $_GET['action'] == 'batch_update') {
    // *** FIX FOR JSON ERROR: START OUTPUT BUFFERING ***
    // This will catch and suppress any unexpected PHP warnings/notices (like the <br /> <b>) 
    // that could corrupt the JSON output.
    ob_start(); 
    
    header('Content-Type: application/json');

    // --- CRITICAL CHANGE: Set fixed effective start date ---
    $effective_start_date = '2025-01-01'; 

    // The old commitment record will still be closed yesterday to ensure continuity
    $yesterday = date('Y-m-d', strtotime('-1 day'));
    $loggedInUserId = $GLOBALS['loggedInUserId'];

    // Fetch All Active Agreements
    $sql_agreements = "
        SELECT 
            pa.agreement_id, 
            pa.partnership_type_id
        FROM Partnership_Agreements pa
        WHERE pa.status = 'Active'
    ";

    $result_agreements = $conn->query($sql_agreements);

    if ($result_agreements === FALSE) {
        // Clear buffer before sending JSON error
        ob_end_clean(); 
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => "Error fetching agreements: " . $conn->error]);
        exit;
    }

    $processed_count = 0;
    $updated_count = 0;
    $skipped_count = 0;
    $error_count = 0;
    $details = [];

    while ($agreement = $result_agreements->fetch_assoc()) {
        $processed_count++;
        $agreement_id = $agreement['agreement_id'];
        $type_id = (int)$agreement['partnership_type_id'];

        $new_commitment_amount = $commitment_map[$type_id] ?? 0.00;
        
        $commitment_currency = 'TZS'; 
        $commitment_frequency = 'Monthly'; 

        if ($new_commitment_amount == 0.00) {
            $error_count++;
            $details[] = ['agreement_id' => $agreement_id, 'status' => 'error', 'message' => "Unmapped type ID {$type_id}."];
            continue;
        }

        // --- Fetch Current Active Commitment ---
        $sql_current_commitment = "
            SELECT 
                commitment_history_id, 
                commitment_amount
            FROM Agreement_Commitment_History
            WHERE agreement_id = ? AND effective_end_date IS NULL
            ORDER BY commitment_history_id DESC LIMIT 1
        ";
        
        $stmt_current = $conn->prepare($sql_current_commitment);
        if (!$stmt_current) {
            $error_count++;
            $details[] = ['agreement_id' => $agreement_id, 'status' => 'error', 'message' => "Prep error: " . $conn->error];
            continue;
        }
        $stmt_current->bind_param("i", $agreement_id);
        $stmt_current->execute();
        $result_current = $stmt_current->get_result();
        $current_commitment = $result_current->fetch_assoc();
        $stmt_current->close();

        // Start transaction
        $conn->begin_transaction();
        $action_taken = false;

        try {
            $current_amount = $current_commitment ? (float)$current_commitment['commitment_amount'] : 0.00;

            if (abs($current_amount - $new_commitment_amount) < 0.01) { 
                // Case A: Amount is already correct
                $skipped_count++;
                $details[] = ['agreement_id' => $agreement_id, 'status' => 'skipped', 'message' => "Amount already correct ({$current_amount})"];
            } else {
                // Case B: Amount needs to be updated (Requires closing old and opening new)
                
                // 1. Close the existing commitment record if one exists
                if ($current_commitment) {
                    $current_id = $current_commitment['commitment_history_id'];
                    $sql_close_old = "
                        UPDATE Agreement_Commitment_History
                        SET effective_end_date = ?, updated_by_user_id = ?, updated_at=NOW()
                        WHERE commitment_history_id = ?
                    ";
                    $stmt_close = $conn->prepare($sql_close_old);
                    $stmt_close->bind_param("sii", $yesterday, $loggedInUserId, $current_id);
                    $stmt_close->execute();
                    $stmt_close->close();
                }

                // 2. Insert the new commitment record (starting on the fixed date)
                $sql_insert_new = "
                    INSERT INTO Agreement_Commitment_History 
                    (agreement_id, commitment_amount, commitment_currency, commitment_frequency, effective_start_date, effective_end_date, created_by_user_id)
                    VALUES (?, ?, ?, ?, ?, NULL, ?)
                ";
                $stmt_insert = $conn->prepare($sql_insert_new);
                $stmt_insert->bind_param("idsssi", 
                    $agreement_id, 
                    $new_commitment_amount, 
                    $commitment_currency, 
                    $commitment_frequency, 
                    $effective_start_date, // <-- Using the fixed date here
                    $loggedInUserId
                );
                $stmt_insert->execute();
                $stmt_insert->close();
                
                $updated_count++;
                $action_taken = true;
                $details[] = ['agreement_id' => $agreement_id, 'status' => 'updated', 'message' => "Updated from {$current_amount} to {$new_commitment_amount} (Effective {$effective_start_date})"];
            }

            $conn->commit();

        } catch (Exception $e) {
            $conn->rollback();
            $error_count++;
            $details[] = ['agreement_id' => $agreement_id, 'status' => 'rollback', 'message' => "DB Error: " . $e->getMessage()];
        }
    }

    // *** FIX FOR JSON ERROR: CLEAN AND STOP OUTPUT BUFFERING ***
    ob_end_clean();

    // Return JSON summary
    echo json_encode([
        'status' => 'success',
        'message' => 'Batch commitment update completed.',
        'processed' => $processed_count,
        'updated' => $updated_count,
        'skipped' => $skipped_count,
        'errors' => $error_count,
        'details' => $details // Optional detailed log
    ]);
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Commitment Batch Update</title>
    <!-- Assuming Bootstrap 5 for quick styling -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .container {
            max-width: 800px;
            margin-top: 50px;
        }
        .update-card {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            border-radius: 12px;
            padding: 30px;
            background-color: #fff;
        }
        /* Simple Modal Styling - Using a standard Bootstrap modal */
        #progressModal .modal-content {
            border-radius: 15px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="update-card">
            <h2 class="mb-4 text-center text-primary">Partnership Commitment Batch Updater</h2>
            <p class="lead text-center">
                This tool will automatically recalculate and update the active commitment amount for ALL active partnership agreements based on their assigned partnership type.
            </p>
            <div class="alert alert-warning my-4" role="alert">
                <strong>Warning:</strong> This process will create new history records in 
                <code>Agreement_Commitment_History</code> for any changed commitments.
                Commitments will be effective as of <strong>2025-01-01</strong>.
            </div>

            <div class="text-center mt-5">
                <button id="updateButton" class="btn btn-primary btn-lg px-5 shadow-sm" onclick="startBatchUpdate()">
                    <i class="fas fa-sync-alt me-2"></i> Run Batch Update
                </button>
            </div>
        </div>
        
        <!-- Progress Modal (Simulating a Progress Dialog) -->
        <div class="modal fade" id="progressModal" tabindex="-1" aria-labelledby="progressModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="progressModalLabel">Processing Update...</h5>
                    </div>
                    <div class="modal-body">
                        <div id="progressMessage" class="mb-3">Fetching agreements and checking for commitment changes...</div>
                        <div class="progress">
                            <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100">Working...</div>
                        </div>
                        <div id="resultsSummary" class="mt-3" style="display:none;">
                            <p><strong>Total Processed:</strong> <span id="processedCount">0</span></p>
                            <p><strong>Commitments Updated:</strong> <span id="updatedCount">0</span></p>
                            <p><strong>Skipped (Already Correct):</strong> <span id="skippedCount">0</span></p>
                            <p class="text-danger"><strong>Errors:</strong> <span id="errorCount">0</span></p>
                            <div class="alert alert-success" id="finalStatus" style="display:none;"></div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" id="closeModalButton" disabled>Close</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS Bundle (Required for modal) and Font Awesome for icons -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script> 
    
    <script>
        const updateButton = document.getElementById('updateButton');
        const progressModal = new bootstrap.Modal(document.getElementById('progressModal'));
        const progressBar = document.getElementById('progressBar');
        const progressMessage = document.getElementById('progressMessage');
        const resultsSummary = document.getElementById('resultsSummary');
        const finalStatus = document.getElementById('finalStatus');
        const closeModalButton = document.getElementById('closeModalButton');
        
        function updateUI(status, message, result = null) {
            progressMessage.textContent = message;
            
            if (status === 'start') {
                progressBar.classList.add('progress-bar-animated', 'progress-bar-striped');
                progressBar.classList.remove('bg-success', 'bg-danger', 'bg-info');
                progressBar.style.width = '100%';
                progressBar.textContent = 'Working...';
                updateButton.disabled = true;
                closeModalButton.disabled = true;
                resultsSummary.style.display = 'none';
                finalStatus.style.display = 'none';
                progressModal.show();
            } else if (status === 'complete' && result) {
                progressBar.classList.remove('progress-bar-animated', 'progress-bar-striped');
                progressBar.style.width = '100%';

                document.getElementById('processedCount').textContent = result.processed;
                document.getElementById('updatedCount').textContent = result.updated;
                document.getElementById('skippedCount').textContent = result.skipped;
                document.getElementById('errorCount').textContent = result.errors;

                resultsSummary.style.display = 'block';
                closeModalButton.disabled = false;
                updateButton.disabled = false;
                
                if (result.errors > 0) {
                    progressBar.classList.add('bg-danger');
                    finalStatus.className = 'alert alert-danger';
                    finalStatus.textContent = 'Completed with errors. Check console for details.';
                } else if (result.updated > 0) {
                    progressBar.classList.add('bg-success');
                    finalStatus.className = 'alert alert-success';
                    finalStatus.textContent = 'Update successful!';
                } else {
                    progressBar.classList.add('bg-info');
                    finalStatus.className = 'alert alert-info';
                    finalStatus.textContent = 'No changes required.';
                }
                progressBar.textContent = 'Done.';
                finalStatus.style.display = 'block';
            } else if (status === 'error') {
                progressBar.classList.remove('progress-bar-animated', 'progress-bar-striped');
                progressBar.classList.add('bg-danger');
                progressBar.style.width = '100%';
                progressBar.textContent = 'Error!';
                updateButton.disabled = false;
                closeModalButton.disabled = false;
                finalStatus.className = 'alert alert-danger';
                finalStatus.textContent = message;
                finalStatus.style.display = 'block';
            }
        }

        async function startBatchUpdate() {
            updateUI('start', 'Starting batch process...');

            try {
                // AJAX call to the same file with the action parameter
                const response = await fetch('update_amount.php?action=batch_update', {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json'
                    }
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const result = await response.json();
                
                if (result.status === 'success') {
                    updateUI('complete', result.message, result);
                    // Optional: log details to console
                    console.log('Batch Update Details:', result.details);
                } else {
                    // Handle logical error returned by PHP
                    updateUI('error', `PHP Error: ${result.message}`);
                }

            } catch (error) {
                console.error('Fetch error:', error);
                // If it still fails, it means some PHP output is still getting through.
                updateUI('error', `An unexpected error occurred during the update: ${error.message}. Please check your PHP logs for pre-JSON output.`);
            }
        }
    </script>
</body>
</html>