<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// save_financial_contribution.php
// This is the frontend UI page for recording a partnership contribution.

require_once 'db_connect.php';

// --- 1. Data Fetching ---

// Fetch partners
$partners = [];
$sql = "SELECT partner_id, partner_name, partner_code, phone_number1 FROM Partners ORDER BY partner_name";
$res = $conn->query($sql);
if ($res) {
    while ($r = $res->fetch_assoc()) $partners[] = $r;
    $res->free();
}

// Fetch agreements and their LATEST committed amount and currency
// This complex JOIN ensures we only get the single most recent commitment record per agreement.
$agreements = [];
$sql = "
    SELECT
        pa.agreement_id,
        pa.agreement_code,
        pa.partner_id,
        ach.commitment_amount,
        ach.commitment_currency
    FROM
        Partnership_Agreements pa
    LEFT JOIN
        Agreement_Commitment_History ach ON pa.agreement_id = ach.agreement_id
    LEFT JOIN
        Agreement_Commitment_History ach_later ON 
            ach.agreement_id = ach_later.agreement_id AND 
            (
                -- Check for a strictly later effective start date
                ach.effective_start_date < ach_later.effective_start_date OR 
                -- If dates are equal, use the higher ID (more recently inserted) as a tie-breaker
                (ach.effective_start_date = ach_later.effective_start_date AND ach.commitment_history_id < ach_later.commitment_history_id)
            )
    WHERE
        -- Only keep the rows from 'ach' where no 'ach_later' record exists
        ach_later.commitment_history_id IS NULL 
    ORDER BY
        pa.agreement_code;
";

$res = $conn->query($sql);
if ($res) {
    while ($r = $res->fetch_assoc()) $agreements[] = $r;
    $res->free();
}

// --- 2. Message Setup ---

$successMessage = '';
$errorMessage = '';
$receipt = '';

if (!empty($_GET['success']) && $_GET['success'] == 1 && !empty($_GET['receipt'])) {
    $receipt = htmlspecialchars($_GET['receipt']);
    $successMessage = "Contribution recorded successfully! Receipt: <strong>{$receipt}</strong>";
}

if (!empty($_GET['error']) && $_GET['error'] == 1 && !empty($_GET['msg'])) {
    $errorMessage = htmlspecialchars($_GET['msg']);
}

?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Record Partnership Contribution</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background:#f8f9fa }
        .container { max-width:720px; margin-top:28px; background:#fff; padding:24px; border-radius:8px; box-shadow:0 0 10px rgba(0,0,0,.06); }
        #partner_autocomplete_list { position:absolute; z-index:1000; width:100%; max-height:200px; overflow:auto; border:1px solid #ddd; background:#fff; }
        #partner_autocomplete_list div { padding:10px; cursor:pointer; }
        #partner_autocomplete_list div:hover { background:#f0f0f0; }
        /* Style adjustments for date and amount alignment */
        .form-control[type="date"] { padding-right: 8px; }
    </style>
</head>
<body>
<div class="container">
    <a href="partners_view_general_Contribution_details.php" class="btn btn-secondary mb-3">← Back to Partner View</a>
    <h2 class="text-center mb-4">Record Partnership Contribution</h2>

    <!-- Dynamic Alert Boxes (Only visible if modals fail to load) -->
    <?php if ($successMessage && !$errorMessage): ?>
    <div class="alert alert-success d-none d-print-block" id="successAlert">
        ✅ <?php echo $successMessage; ?>
    </div>
    <?php endif; ?>

    <?php if ($errorMessage): ?>
    <div class="alert alert-danger d-none d-print-block" id="errorAlert">
        ❌ Error: <?php echo $errorMessage; ?>
    </div>
    <?php endif; ?>

    <form method="POST" action="save_financial_contribution_ui.php" id="contribForm">
        <div class="mb-3 position-relative">
            <label class="form-label">Partner</label>
            <input type="text" id="partner_search_input" class="form-control" placeholder="Search by Name or Code" autocomplete="off" required>
            <div id="partner_autocomplete_list" style="display:none"></div>
            <input type="hidden" id="partner_id" name="partner_id" required>
        </div>

        <div class="mb-3">
            <label class="form-label">Partnership Agreement</label>
            <select id="agreement_id" name="agreement_id" class="form-select" required>
                <option value="">Select Agreement</option>
            </select>
            <small class="form-text text-muted">The currency will be determined by the agreement's active commitment on the contribution date.</small>
        </div>

        <div class="row mb-4">
            <div class="col-md-6">
                <label class="form-label">Amount</label>
                <input type="number" step="0.01" name="amount" class="form-control" placeholder="e.g., 50000.00" required>
            </div>
            <div class="col-md-6">
                <label class="form-label">Contribution Date</label>
                <input type="date" name="contribution_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
            </div>
        </div>

        <button class="btn btn-primary w-100 py-2" type="submit">Record Contribution</button>
    </form>
</div>

<!-- Modal for Progress/Loading -->
<div class="modal fade" id="progressModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content text-center p-4">
            <div class="spinner-border text-primary mb-3" role="status"></div>
            <h5 class="fw-bold">Processing...</h5>
            <p class="text-muted small">Saving record and attempting to send SMS.</p>
        </div>
    </div>
</div>

<!-- Modal for Success -->
<div class="modal fade" id="successModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content text-center p-4">
            <div class="text-success fs-1 mb-2">🎉</div>
            <h5 class="fw-bold">Contribution Saved!</h5>
            <p class="mt-2 text-wrap" id="successMessageContent"><?php echo $successMessage; ?></p>
            <button class="btn btn-success mt-3" data-bs-dismiss="modal">Close</button>
        </div>
    </div>
</div>

<!-- Modal for Error -->
<div class="modal fade" id="errorModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content p-4">
            <div class="text-danger fs-1 mb-2 text-center">🛑</div>
            <h5 class="fw-bold text-center">Transaction Failed</h5>
            <p class="mt-2 text-muted">An error occurred while saving the contribution:</p>
            <div class="alert alert-warning small" id="errorMessageContent"><?php echo $errorMessage; ?></div>
            <button class="btn btn-danger mt-3" data-bs-dismiss="modal">Dismiss</button>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
const partners = <?php echo json_encode($partners, JSON_UNESCAPED_UNICODE); ?>;
const agreements = <?php echo json_encode($agreements, JSON_UNESCAPED_UNICODE); ?>;

document.addEventListener('DOMContentLoaded', () => {
    const input = document.getElementById('partner_search_input');
    const hid = document.getElementById('partner_id');
    const list = document.getElementById('partner_autocomplete_list');
    const agreementSelect = document.getElementById('agreement_id');
    const form = document.getElementById('contribForm');
    
    // Modals
    const progressModalEl = document.getElementById('progressModal');
    const progressModal = new bootstrap.Modal(progressModalEl);
    
    const successModalEl = document.getElementById('successModal');
    const successModal = new bootstrap.Modal(successModalEl);
    
    const errorModalEl = document.getElementById('errorModal');
    const errorModal = new bootstrap.Modal(errorModalEl);
    
    // PHP messages passed to JS
    const successMessagePHP = "<?php echo $successMessage; ?>";
    const errorMessagePHP = "<?php echo $errorMessage; ?>";


    // 1. Modal Display Logic based on URL params
    if (successMessagePHP) {
        successModal.show();
    } else if (errorMessagePHP) {
        errorModal.show();
    }


    // 2. Form Submission: Show loading modal
    form.addEventListener('submit', (e) => {
        // Simple form validation check before showing modal
        if (form.checkValidity()) {
            progressModal.show();
        }
    });

    // 3. Autocomplete and Agreement Loading Logic
    function showList(items) {
        list.innerHTML = '';
        items.forEach(p => {
            const div = document.createElement('div');
            div.innerHTML = `<strong>${p.partner_name}</strong> (${p.partner_code})`;
            div.addEventListener('click', () => {
                input.value = `${p.partner_name} (${p.partner_code})`;
                hid.value = p.partner_id;
                list.style.display = 'none';
                loadAgreements(p.partner_id);
                // Force validation check after selection
                input.setCustomValidity(""); 
            });
            list.appendChild(div);
        });
        list.style.display = items.length ? 'block' : 'none';
    }

    function loadAgreements(pid) {
        agreementSelect.innerHTML = '<option value="">Select Agreement</option>';
        const filtered = agreements.filter(a => a.partner_id == pid);
        filtered.forEach(a => {
            const opt = document.createElement('option');
            opt.value = a.agreement_id;
            
            // Check if commitment data is available and format for display
            let commitmentInfo = 'No commitment set';
            if (a.commitment_amount && a.commitment_currency) {
                const formattedAmount = Number(a.commitment_amount).toLocaleString('en-US', {minimumFractionDigits: 2});
                commitmentInfo = `Commitment: ${formattedAmount} ${a.commitment_currency}`;
            }

            opt.textContent = `${a.agreement_code} (${commitmentInfo})`;
            agreementSelect.appendChild(opt);
        });
        agreementSelect.disabled = filtered.length === 0;
        agreementSelect.setCustomValidity(filtered.length === 0 ? "No active agreements found for this partner." : "");
    }

    input.addEventListener('input', () => {
        const q = input.value.trim().toLowerCase();
        if (!q) { 
            list.style.display = 'none'; 
            hid.value=''; 
            agreementSelect.innerHTML='<option value="">Select Agreement</option>'; 
            agreementSelect.disabled=true; 
            input.setCustomValidity("Please select a valid partner from the list.");
            return; 
        }
        
        // Reset ID when input changes, until a selection is made
        hid.value = '';

        const matches = partners.filter(p => 
            p.partner_name.toLowerCase().includes(q) || 
            (p.partner_code||'').toLowerCase().includes(q)
        );
        showList(matches);
    });

    // Handle clicking outside the list
    document.addEventListener('click', (e) => {
        if (!input.contains(e.target) && !list.contains(e.target)) {
            list.style.display = 'none';
        }
    });

    // Initial state check
    agreementSelect.disabled = true;
    input.setCustomValidity("Please select a valid partner from the list.");
});
</script>
</body>
</html>