<?php
// partners_view_general_Contribution_details.php
// -----------------------------------------------------
// Start a session to handle status messages
// -----------------------------------------------------
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// -----------------------------------------------------
// Database connection
// -----------------------------------------------------
// NOTE: Assuming 'db_connect.php' establishes connection in $conn variable
include 'db_connect.php';

// -----------------------------------------------------
// Global variable for Partnership Category ID
// This avoids repeated subqueries in the loop.
// -----------------------------------------------------
$partnership_category_id = null;

// Function to safely fetch the Partnership Contribution Category ID
function get_partnership_category_id($conn)
{
    global $partnership_category_id;
    if ($partnership_category_id !== null) {
        return $partnership_category_id;
    }

    // Find the category ID for contributions related to partnerships
    $sql = "SELECT category_id FROM Sadaka_Categories WHERE category_name = 'Partnership Contribution'";
    $result = $conn->query($sql);

    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $partnership_category_id = $row['category_id'];
        return $partnership_category_id;
    }

    // Handle case where category is not found (Critical Error)
    die('Error: "Partnership Contribution" category not found in Sadaka_Categories.');
}

// -----------------------------------------------------
// Helper function to safely fetch request params
// -----------------------------------------------------
function get_safe_data($param, $default = '')
{
    return isset($_REQUEST[$param]) ? htmlspecialchars($_REQUEST[$param]) : $default;
}

// -----------------------------------------------------
// Handle search filters and determine date range
// -----------------------------------------------------
$search_month_year  = get_safe_data('month_year_filter');
$search_query       = get_safe_data('search_query'); // Single search input: Partner Code/Name
$search_start_date  = get_safe_data('start_date_filter'); // Date Range Start (YYYY-MM-DD)
$search_end_date    = get_safe_data('end_date_filter');  // Date Range End (YYYY-MM-DD)

// Variables for SQL queries and display
$paid_start_date = '';
$paid_end_date   = '';
$display_month_year = 'No Period Selected';

// Logic to determine the period based on filter priority:
// 1. Date Range Filter (Start/End Date)
if (!empty($search_start_date) && !empty($search_end_date)) {
    $paid_start_date = $search_start_date;
    $paid_end_date   = $search_end_date;
    $display_month_year = "From " . $search_start_date . " to " . $search_end_date;
} 
// 2. Month/Year Filter (Legacy compatibility)
elseif (!empty($search_month_year)) {
    $date_obj = DateTime::createFromFormat('F Y', $search_month_year);
    if ($date_obj) {
        // Calculate the first and last day of the month/year selected
        $paid_start_date = $date_obj->format('Y-m-01');
        $paid_end_date   = $date_obj->format('Y-m-t');
    }
    $display_month_year = $search_month_year;
} 
// 3. Default: Current Month/Year (if no filter is set) - This ensures data is visible on initial load.
else {
    $current_date_obj = new DateTime('now');
    $paid_start_date = $current_date_obj->format('Y-m-01');
    $paid_end_date   = $current_date_obj->format('Y-m-t');
    $display_month_year = $current_date_obj->format('F Y') . ' (Default)';
}

// -----------------------------------------------------
// Handle SMS Status Message after a redirect
// -----------------------------------------------------
$sms_status_message = '';
if (isset($_SESSION['sms_status'])) {
    $status = $_SESSION['sms_status'];
    $sms_status_message = '<div class="alert alert-' . htmlspecialchars($status['type']) . '">'
                        . htmlspecialchars($status['message']) . '</div>';
    unset($_SESSION['sms_status']); // Clear the session variable
}

// Get the required category ID once
$partnership_category_id = get_partnership_category_id($conn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Partnership Contributions Overview</title>

    <!-- Bootstrap and Datepicker CSS -->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" rel="stylesheet">

    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f0f4f8;
            padding: 20px;
        }
        .container {
            background-color: #fff;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        h2 {
            color: #1e3a8a;
            font-weight: 700;
            margin-bottom: 20px;
            border-bottom: 2px solid #3b82f6;
            padding-bottom: 10px;
        }
        .filter-form {
            margin-bottom: 25px;
            padding: 20px;
            border: 1px solid #cceeff;
            border-radius: 8px;
            background-color: #f9faff;
        }
        .form-group label {
            font-weight: 600;
            color: #333;
        }
        .table th,
        .table td {
            vertical-align: middle;
            font-size: 0.9rem;
        }
        .btn-action {
            margin-right: 5px;
            margin-bottom: 5px; 
            border-radius: 6px;
        }
        .btn-view-all-contributions {
            background-color: #f97316; /* Tailwind orange-600 */
            border-color: #f97316;
            color: #fff;
            transition: background-color 0.3s;
        }
        .btn-view-all-contributions:hover {
            background-color: #ea580c; /* Tailwind orange-700 */
            border-color: #ea580c;
            color: #fff;
        }
        .color-red { color: #dc2626; font-weight: 600; }
        .color-black { color: #1f2937; }
        .color-green { color: #16a34a; font-weight: 600; }
        .color-darkgreen { color: #059669; font-weight: 700; }
    </style>
</head>
<body>

<div class="container">
    <h2>Partnership Contributions Report</h2>

    <div class="mb-4">
        <a href="index2.php" class="btn btn-secondary rounded-lg">Back to Dashboard</a>
        <a href="save_financial_contribution.php" class="btn btn-primary rounded-lg">Record New Contribution</a>
    </div>
    
    <?php echo $sms_status_message; ?>

    <div class="filter-form">
        <form action="" method="GET" class="form-inline" id="filterForm">
            <div class="form-group mr-3 mb-2">
                <label for="month_year_filter" class="mr-2">Filter by Month/Year:</label>
                <input type="text" class="form-control datepicker-month-year rounded-lg"
                        id="month_year_filter"
                        name="month_year_filter"
                        placeholder="Select Month/Year"
                        value="<?php echo $search_month_year; ?>">
            </div>

            <div class="form-group mr-3 mb-2">
                <label for="start_date_filter" class="mr-2">Start Date:</label>
                <input type="text" class="form-control datepicker-date rounded-lg"
                        id="start_date_filter"
                        name="start_date_filter"
                        placeholder="YYYY-MM-DD"
                        value="<?php echo $search_start_date; ?>">
            </div>
            <div class="form-group mr-3 mb-2">
                <label for="end_date_filter" class="mr-2">End Date:</label>
                <input type="text" class="form-control datepicker-date rounded-lg"
                        id="end_date_filter"
                        name="end_date_filter"
                        placeholder="YYYY-MM-DD"
                        value="<?php echo $search_end_date; ?>">
            </div>

            <div class="form-group mr-3 mb-2">
                <label for="search_query" class="mr-2">Search Partner (Code/Name):</label>
                <input type="text" class="form-control rounded-lg"
                        id="search_query"
                        name="search_query"
                        value="<?php echo $search_query; ?>"
                        placeholder="Code or Name">
            </div>

            <button type="submit" class="btn btn-primary rounded-lg mb-2" id="applyFiltersButton">Apply Filters</button>
            <a href="partners_view_general_Contribution_details.php" class="btn btn-secondary rounded-lg ml-2 mb-2">Clear Filters</a>
        </form>
        <p class="text-muted mt-2 mb-0">
            Current Analysis Period: <span class="font-weight-bold"><?php echo htmlspecialchars($display_month_year); ?></span>
        </p>
    </div>

    <table class="table table-striped table-hover table-bordered">
        <thead class="bg-primary text-white">
        <tr>
            <th>#</th>
            <th>Partner Name</th>
            <th>Partner Code</th>
            <th>Agreement Type</th>
            <th>Commitment Amount (<?php echo $display_month_year; ?>)</th>
            <th>Total Paid (<?php echo $display_month_year; ?>)</th>
            <th>Remaining Amount (<?php echo $display_month_year; ?>)</th>
            <th>Actions</th>
        </tr>
        </thead>
        <tbody>
        <?php
        // -----------------------------------------------------
        // Build the main query to fetch Partners and their Active Agreements
        // -----------------------------------------------------
        $sql = "
            SELECT
                p.partner_id,
                p.partner_name,
                p.partner_code,
                p.phone_number1,
                pa.agreement_id,
                pa.status AS agreement_status,
                pt.type_name AS partnership_type_name
            FROM
                Partners p
            JOIN
                Partnership_Agreements pa ON p.partner_id = pa.partner_id
            JOIN
                Partnership_Types pt ON pa.partnership_type_id = pt.partnership_type_id
            WHERE 1=1
        ";

        $params = [];
        $types  = "";

        // 3. Apply Partner Code/Name search filter (Combines Code and Name search)
        if (!empty($search_query)) {
            $sql .= " AND (p.partner_code LIKE ? OR p.partner_name LIKE ?)";
            $params[] = '%' . $search_query . '%';
            $params[] = '%' . $search_query . '%';
            $types .= "ss";
        }
        
        // Filter only for active agreements to reduce the dataset
        $sql .= " AND pa.status = 'Active'";

        $sql .= " ORDER BY p.partner_name";

        $stmt = $conn->prepare($sql);
        if ($stmt === false) {
            die('Error preparing statement: ' . $conn->error);
        }

        if (!empty($params)) {
            // Use call_user_func_array for dynamic binding
            $stmt->bind_param($types, ...$params);
        }

        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $index = 1;
            while ($row = $result->fetch_assoc()) {
                $partner_id          = $row['partner_id'];
                $agreement_id        = $row['agreement_id'];
                $phone_number        = $row['phone_number1'];
                
                // Initialize values
                $commitment_amount = 0;
                $commitment_currency = 'TZS'; 
                $total_paid_this_period = 0;
                $remaining_amount = 0;
                $commitment_frequency = 'Monthly'; 

                // Proceed with commitment and payment calculation ONLY if a valid period is set
                if (!empty($paid_start_date) && !empty($paid_end_date)) {
                    
                    // -----------------------------------------------------
                    // 5 & 6. Determine the Commitment Amount for the period (New Schema)
                    // The query finds the commitment history row that was effective at the start of the filter period.
                    // -----------------------------------------------------
                    $sql_commitment = "
                        SELECT 
                            ach.commitment_amount,
                            ach.commitment_currency,
                            ach.commitment_frequency
                        FROM 
                            Agreement_Commitment_History ach
                        WHERE 
                            ach.agreement_id = ?
                            AND ach.effective_start_date <= ? 
                            AND (ach.effective_end_date IS NULL OR ach.effective_end_date >= ?)
                        ORDER BY 
                            ach.effective_start_date DESC
                        LIMIT 1
                    ";

                    $stmt_commitment = $conn->prepare($sql_commitment);
                    if ($stmt_commitment) {
                        // Use the START date of the filter period to find the active commitment
                        $stmt_commitment->bind_param("iss", $agreement_id, $paid_start_date, $paid_start_date); 
                        $stmt_commitment->execute();
                        $result_commitment = $stmt_commitment->get_result();
                        
                        if ($row_commitment = $result_commitment->fetch_assoc()) {
                            $commitment_amount = $row_commitment['commitment_amount'];
                            $commitment_currency = $row_commitment['commitment_currency'];
                            $commitment_frequency = $row_commitment['commitment_frequency'];
                        }
                        $stmt_commitment->close();
                    } else {
                        error_log('Error preparing commitment statement: ' . $conn->error);
                    }


                    // -----------------------------------------------------
                    // 5 & 6. Calculate Total Paid for the period (New Schema)
                    // Use partner_id, agreement_id, and contribution_date range
                    // -----------------------------------------------------
                    $sql_paid = "
                        SELECT SUM(fc.amount) AS total_paid
                        FROM Financial_Contributions fc
                        WHERE fc.partner_id = ?
                          AND fc.agreement_id = ?
                          AND fc.category_id = ?
                          AND fc.contribution_date BETWEEN ? AND ?
                    ";

                    $stmt_paid = $conn->prepare($sql_paid);
                    if ($stmt_paid) {
                        $stmt_paid->bind_param("iiiss", $partner_id, $agreement_id, $partnership_category_id, $paid_start_date, $paid_end_date);
                        $stmt_paid->execute();
                        $result_paid = $stmt_paid->get_result();
                        $row_paid    = $result_paid->fetch_assoc();
                        $total_paid_this_period = $row_paid['total_paid'] ?? 0;
                        $stmt_paid->close();
                    } else {
                        error_log('Error preparing paid statement: ' . $conn->error);
                    }
                }
                
                // 7. Final calculations
                $remaining_amount = $commitment_amount - $total_paid_this_period;

                // Determine colors for remaining amount
                $remaining_amount_color_class = 'color-black';
                if ($commitment_amount > 0 && $remaining_amount > 0) {
                    $remaining_amount_color_class = 'color-red';
                } elseif ($commitment_amount > 0 && $remaining_amount <= 0) {
                    $remaining_amount_color_class = 'color-darkgreen'; // Fully paid or overpaid
                }

                // Determine colors for total paid
                $total_paid_color_class = 'color-black';
                if ($total_paid_this_period > 0 && $total_paid_this_period < $commitment_amount) {
                    $total_paid_color_class = 'color-green';
                } elseif ($total_paid_this_period >= $commitment_amount && $total_paid_this_period > 0) {
                    $total_paid_color_class = 'color-darkgreen';
                }
                ?>
                <tr>
                    <td><?php echo $index++; ?></td>
                    <td class="partner-name"><?php echo htmlspecialchars($row['partner_name']); ?></td>
                    <td class="partner-code"><?php echo htmlspecialchars($row['partner_code']); ?></td>
                    <td><?php echo htmlspecialchars($row['partnership_type_name']); ?></td>
                    <td><?php echo number_format($commitment_amount, 2) . ' ' . htmlspecialchars($commitment_currency) . ' (' . htmlspecialchars($commitment_frequency) . ')'; ?></td>
                    <td class="<?php echo $total_paid_color_class; ?>">
                        <?php echo number_format($total_paid_this_period, 2) . ' ' . htmlspecialchars($commitment_currency); ?>
                    </td>
                    <td class="<?php echo $remaining_amount_color_class; ?>">
                        <?php echo number_format($remaining_amount, 2) . ' ' . htmlspecialchars($commitment_currency); ?>
                    </td>
                    <td>
                        <!-- View More (Relies on Month/Year legacy filter) -->
                        <a href="individual_partner_details.php?partner_id=<?php echo $row['partner_id']; ?>&agreement_id=<?php echo $row['agreement_id']; ?>&month_year=<?php echo urlencode($search_month_year); ?>"
                            class="btn btn-info btn-sm btn-action view-more-btn rounded-lg">View More</a>

                        <!-- View All Contributions (Relies on Start/End Date filter) -->
                        <a href="contribution_by_date.php?partner_id=<?php echo $row['partner_id']; ?>&agreement_id=<?php echo $row['agreement_id']; ?>&start_date=<?php echo urlencode($paid_start_date); ?>&end_date=<?php echo urlencode($paid_end_date); ?>"
                            class="btn btn-view-all-contributions btn-sm btn-action view-contributions-range-btn rounded-lg"
                            data-partner-code="<?php echo htmlspecialchars($row['partner_code']); ?>"
                            data-partner-name="<?php echo htmlspecialchars($row['partner_name']); ?>"
                            <?php echo (empty($paid_start_date) || empty($paid_end_date)) ? 'disabled' : ''; ?>
                            >
                            View Contributions
                        </a>
                        
                        <!-- Send SMS (Relies on calculated amounts for the period) -->
                        <button type="button" class="btn btn-success btn-sm btn-action send-sms-btn rounded-lg"
                                 data-toggle="modal"
                                 data-target="#sendSmsModal"
                                 data-partner-id="<?php echo $row['partner_id']; ?>"
                                 data-partner-code="<?php echo htmlspecialchars($row['partner_code']); ?>"
                                 data-partner-name="<?php echo htmlspecialchars($row['partner_name']); ?>"
                                 data-phone-number="<?php echo htmlspecialchars($phone_number); ?>"
                                 data-commitment-amount="<?php echo $commitment_amount; ?>"
                                 data-total-paid="<?php echo $total_paid_this_period; ?>"
                                 data-remaining-amount="<?php echo $remaining_amount; ?>"
                                 data-month-year="<?php echo htmlspecialchars($display_month_year); // Use the calculated display value ?>"
                                 data-commitment-currency="<?php echo htmlspecialchars($commitment_currency); ?>"
                                 <?php echo (empty($paid_start_date) || empty($paid_end_date)) ? 'disabled' : ''; ?>>
                            Send SMS
                        </button>
                    </td>
                </tr>
                <?php
            }
        } else {
            echo '<tr><td colspan="8" class="text-center">No active partnership agreements found matching the search criteria.</td></tr>';
        }
        $stmt->close();
        ?>
        </tbody>
    </table>
</div>

<!-- Modal for Sending SMS -->
<div class="modal fade" id="sendSmsModal" tabindex="-1" role="dialog" aria-labelledby="sendSmsModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content rounded-xl shadow-2xl">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="sendSmsModalLabel">Send SMS to Partner</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>

            <form id="sendSmsForm">
                <div class="modal-body">
                    <!-- Hidden fields to pass data to AJAX -->
                    <input type="hidden" name="partner_id" id="modalPartnerId">
                    <input type="hidden" name="partner_code" id="modalPartnerCode">
                    <input type="hidden" name="commitment_amount" id="modalCommitmentAmount">
                    <input type="hidden" name="total_paid" id="modalTotalPaid">
                    <input type="hidden" name="remaining_amount" id="modalRemainingAmount">
                    <input type="hidden" name="commitment_currency" id="modalCommitmentCurrency">
                    <input type="hidden" name="partnership_category_id" value="<?php echo $partnership_category_id; ?>">

                    <div class="form-group">
                        <label for="modalPartnerName">Partner Name:</label>
                        <input type="text" class="form-control" id="modalPartnerName" readonly>
                    </div>

                    <div class="form-group">
                        <label for="modalPhoneNumber">Phone Number:</label>
                        <input type="text" class="form-control" id="modalPhoneNumber" name="phone_number" required>
                    </div>

                    <div class="form-group">
                        <label for="modalMonthYear">Period (from filter):</label>
                        <input type="text" class="form-control" id="modalMonthYear" name="month_year" readonly required>
                    </div>

                    <div class="form-group">
                        <label for="smsType">SMS Type:</label>
                        <select class="form-control" id="smsType" name="sms_category_id" required>
                            <option value="">Select SMS Type</option>
                            <option value="2">Partnership Thanks</option>
                            <option value="3">Partnership Reminder</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="smsMessage">Message Content:</label>
                        <textarea class="form-control" id="smsMessage" name="message_content" rows="4" readonly></textarea>
                    </div>

                    <div id="smsStatusMessage" class="mt-3"></div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary rounded-lg" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-success rounded-lg" id="sendSmsButton">Send SMS</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Footer Scripts -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <!-- Datepicker JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/locales/bootstrap-datepicker.en-GB.min.js"></script>
    <script>
        $(document).ready(function() {
            // 1. Month/Year Datepicker
            $('.datepicker-month-year').datepicker({
                format: "MM yyyy",
                startView: "months",
                minViewMode: "months",
                autoclose: true,
                orientation: "bottom auto"
            });

            // 2. Standard Datepicker for Start/End Date
            $('.datepicker-date').datepicker({
                format: "yyyy-mm-dd", // Consistent format for SQL querying
                autoclose: true,
                orientation: "bottom auto",
                todayHighlight: true
            });

            // -----------------------------------------------------
            // Dynamic Search Filter (Requirement 1)
            // -----------------------------------------------------
            let typingTimer; // Timer identifier
            const doneTypingInterval = 500; // Time in milliseconds (0.5 second)

            $('#search_query').on('keyup', function () {
                clearTimeout(typingTimer);
                if ($('#search_query').val().length >= 2 || $('#search_query').val().length === 0) {
                    // Set a new timer to submit the form after the delay
                    typingTimer = setTimeout(function() {
                        $('#filterForm').submit();
                    }, doneTypingInterval);
                }
            });
            
            // Prevent auto-submit on keyup from interfering with manual button click
            $('#applyFiltersButton').on('click', function() {
                clearTimeout(typingTimer);
            });


            // -----------------------------------------------------
            // Logic: Enable/Disable buttons based on filter selection
            // -----------------------------------------------------
            function checkFilterStatus() {
                var startDate = $('#start_date_filter').val();
                var endDate = $('#end_date_filter').val();
                var monthYear = $('#month_year_filter').val();
                
                // Active period: True if Start/End Date are set OR if Month/Year is set
                var hasActivePeriod = (startDate !== '' && endDate !== '') || (monthYear !== '');

                // Control action buttons based on whether a period is set for calculation
                $('.send-sms-btn, .view-contributions-range-btn').each(function() {
                    if (hasActivePeriod) {
                        $(this).prop('disabled', false).removeClass('disabled');
                    } else {
                        $(this).prop('disabled', true).addClass('disabled');
                    }
                });
                
                // Control 'View More' button (legacy link - usually handles individual months)
                $('.view-more-btn').each(function() {
                    if (monthYear !== '') {
                        $(this).prop('disabled', false).removeClass('disabled');
                    } else {
                        $(this).prop('disabled', true).addClass('disabled');
                    }
                });

            }

            // Run the check on page load and whenever filters change
            checkFilterStatus();
            $('#filterForm input').on('change keyup', checkFilterStatus);
            
            // -----------------------------------------------------
            // Modal/SMS Logic 
            // -----------------------------------------------------

            // Handle "Send SMS" button click to populate modal
            $('#sendSmsModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget); 
                var partnerId = button.data('partner-id');
                var partnerCode = button.data('partner-code');
                var partnerName = button.data('partner-name');
                var phoneNumber = button.data('phone-number');
                var commitmentAmount = button.data('commitment-amount');
                var totalPaid = button.data('total-paid');
                var remainingAmount = button.data('remaining-amount');
                var monthYear = button.data('month-year');
                var commitmentCurrency = button.data('commitment-currency');

                var modal = $(this);
                modal.find('#modalPartnerId').val(partnerId);
                modal.find('#modalPartnerCode').val(partnerCode);
                modal.find('#modalPartnerName').val(partnerName);
                modal.find('#modalPhoneNumber').val(phoneNumber);
                modal.find('#modalMonthYear').val(monthYear);
                modal.find('#modalCommitmentAmount').val(commitmentAmount);
                modal.find('#modalTotalPaid').val(totalPaid);
                modal.find('#modalRemainingAmount').val(remainingAmount);
                modal.find('#modalCommitmentCurrency').val(commitmentCurrency);
                
                modal.find('#smsStatusMessage').html(''); // Clear previous messages
                modal.find('#smsMessage').val(''); // Clear previous message content
                modal.find('#smsType').val(''); // Reset SMS type selection
                modal.find('#sendSmsButton').prop('disabled', true).text('Send SMS'); // Start disabled until type selected

                // Display a warning if the SMS period is a date range instead of a single month/year
                if (monthYear.includes('From ') && monthYear.includes(' to ')) {
                     modal.find('#smsStatusMessage').html('<div class="alert alert-info">The period is a **Date Range**. Generated SMS will reference this range.</div>');
                }
            });

            // Dynamically generate SMS message based on type and status
            $('#smsType').on('change', function() {
                var smsType = $(this).val();
                var partnerId = $('#modalPartnerId').val();
                var partnerCode = $('#modalPartnerCode').val();
                var partnerName = $('#modalPartnerName').val();
                var monthYear = $('#modalMonthYear').val();
                var remainingAmount = parseFloat($('#modalRemainingAmount').val());
                var totalPaid = parseFloat($('#modalTotalPaid').val());
                var commitmentAmount = parseFloat($('#modalCommitmentAmount').val());
                var commitmentCurrency = $('#modalCommitmentCurrency').val();
                var smsMessage = '';

                // Get initial status HTML (like date range info)
                var primaryStatusHtml = $('#smsStatusMessage').html().split('<div class="alert mt-2"')[0] || '';
                $('#smsStatusMessage').html(primaryStatusHtml);
                
                if (monthYear.includes('No Period Selected')) {
                    $('#smsStatusMessage').html('<div class="alert alert-danger">Cannot generate SMS. Please select a valid period using the filters.</div>');
                    $('#smsMessage').val('');
                    $('#sendSmsButton').prop('disabled', true);
                    return;
                }
                
                $('#sendSmsButton').prop('disabled', false); // Re-enable by default

                // Generate Message
                if (smsType === '2') { // Partnership Thanks
                    if (totalPaid >= commitmentAmount && totalPaid > 0) { // Fully paid or overpaid
                        smsMessage = `Asante ndugu ${partnerName}, kwa mchango wako wa Haleluya TV Partners kwa kipindi cha ${monthYear}. Mungu akubariki sana!`;
                        $('#smsStatusMessage').append('<div class="alert alert-success mt-2">This will send a "Thanks" message for full contribution.</div>');
                    } else if (totalPaid > 0 && totalPaid < commitmentAmount) {
                        smsMessage = `Asante ndugu ${partnerName}, kwa mchango wako wa Haleluya TV Partners kwa kipindi cha ${monthYear}. Kiasi kilichobaki: ${remainingAmount.toFixed(2)} ${commitmentCurrency}. Tafadhali kamilisha mchango wako.`;
                        $('#smsStatusMessage').append('<div class="alert alert-warning mt-2">The partner has partially contributed. This sends a "Thanks" message with a reminder for the remaining amount.</div>');
                    }
                    else { // Total Paid is 0
                        smsMessage = `Asante ndugu ${partnerName}, kwa kushirikiana na Haleluya TV Partners. Tafadhali kumbuka mchango wako wa kipindi cha ${monthYear} ili tuweze kufikia malengo yetu.`;
                        $('#smsStatusMessage').append('<div class="alert alert-warning mt-2">The partner has no recorded contributions for this period. This sends a polite "Thanks/Reminder".</div>');
                    }
                } else if (smsType === '3') { // Partnership Reminder
                    if (remainingAmount > 0) {
                        smsMessage = `Ndugu ${partnerName}, unakumbushwa kukamilisha mchango wako wa Haleluya TV Partners kwa kipindi cha ${monthYear}. Kiasi kilichobaki: ${remainingAmount.toFixed(2)} ${commitmentCurrency}.`;
                        $('#smsStatusMessage').append('<div class="alert alert-info mt-2">This will send a "Reminder" message for outstanding amount.</div>');
                    } else if (commitmentAmount > 0 && remainingAmount <= 0) {
                        smsMessage = `Ndugu ${partnerName}, umekamilisha mchango wako wa Haleluya TV Partners kwa kipindi cha ${monthYear}. Asante kwa uaminifu wako!`;
                        $('#smsStatusMessage').append('<div class="alert alert-success mt-2">The partner has already completed their contribution for this period. This will send a "Completion Confirmation" message.</div>');
                    } else { // No commitment/paid amount, but filter is active
                         smsMessage = `Ndugu ${partnerName}, unakumbushwa kuhusu utaratibu wa mchango wako wa Haleluya TV Partners kwa kipindi cha ${monthYear}. Tafadhali wasiliana nasi kwa uthibitisho.`;
                        $('#smsStatusMessage').append('<div class="alert alert-warning mt-2">Commitment is zero or paid is zero. Sends a general reminder.</div>');
                    }
                } else {
                    smsMessage = '';
                    $('#smsStatusMessage').append('');
                    $('#sendSmsButton').prop('disabled', true);
                }
                $('#smsMessage').val(smsMessage);

                // Check SMS_Log to prevent duplicates or warn
                if(smsMessage !== '' && smsType !== '') {
                    checkSmsSentStatus(smsType, partnerId, monthYear, partnerCode);
                } else {
                     $('#sendSmsButton').prop('disabled', true);
                }
            });

            // Function to check if an SMS of this type/period has already been sent
            function checkSmsSentStatus(smsCategory, partnerId, monthYear, partnerCode) {
                if (smsCategory && partnerId && monthYear) {
                    $.ajax({
                        url: 'check_sms_status.php',
                        method: 'POST',
                        dataType: 'json',
                        data: {
                            partner_id: partnerId,
                            month_year: monthYear,
                            sms_category_id: smsCategory,
                            partner_code: partnerCode
                        },
                        success: function(response) {
                            var statusHtml = '';
                            if (response.status === 'exists') {
                                statusHtml = '<div class="alert alert-warning mt-2">ALERT: ' + response.message + '</div>';
                                // Use a custom modal or better prompt if possible, but using confirm for simplicity
                                if (confirm('An SMS of this type for this partner and period has already been sent. Do you want to send it again?')) {
                                    $('#sendSmsButton').prop('disabled', false); // Enable if user confirms
                                } else {
                                    $('#sendSmsButton').prop('disabled', true); // Disable if user cancels
                                }
                            } else {
                                statusHtml = '<div class="alert alert-info mt-2">Status: This SMS has not been sent before for this partner and period.</div>';
                                $('#sendSmsButton').prop('disabled', false); // Enable if not sent before
                            }
                            // Append the status message
                            $('#smsStatusMessage').append(statusHtml);
                        },
                        error: function(xhr, status, error) {
                            console.error("AJAX Error: " + status + error);
                            $('#smsStatusMessage').append('<div class="alert alert-danger mt-2">Error checking SMS status. Cannot proceed.</div>');
                            $('#sendSmsButton').prop('disabled', true); // Disable on error
                        }
                    });
                }
            }

            // 4. Handle SMS form submission with AJAX 
            $('#sendSmsForm').on('submit', function(e) {
                e.preventDefault(); 

                if (!confirm("Are you sure you want to send this SMS? This action is irreversible.")) {
                    return false;
                }

                $('#sendSmsButton').prop('disabled', true).text('Sending...');
                $('#smsStatusMessage').html('<div class="alert alert-info">Sending SMS... Please wait.</div>');

                $.ajax({
                    url: 'send_sms_for_partners_view_general_Contribution_details.php', // Assuming this script exists and works
                    method: 'POST',
                    data: $(this).serialize(), 
                    dataType: 'json', 
                    success: function(response) {
                        if (response.status === 'success') {
                            $('#smsStatusMessage').html('<div class="alert alert-success">' + response.message + '</div>');
                            // Optionally, close the modal: $('#sendSmsModal').modal('hide');
                        } else {
                            var alert_type = response.status === 'error' ? 'danger' : 'warning';
                            $('#smsStatusMessage').html('<div class="alert alert-' + alert_type + '">' + response.message + '</div>');
                        }
                    },
                    error: function(xhr, status, error) {
                        var error_message = "Network/Server Error: Failed to send SMS.";
                        $('#smsStatusMessage').html('<div class="alert alert-danger">' + error_message + '</div>');
                        console.error("AJAX Error: " + status + error + ". Response: " + xhr.responseText);
                    },
                    complete: function() {
                        $('#sendSmsButton').prop('disabled', false).text('Send SMS');
                    }
                });
            });
        });
    </script>
</body>
</html>
<?php $conn->close(); ?>