<?php
require_once 'config/init.php';
require_once 'includes/auth.php';
requireAuth();

$db = getDB();

// Get date range from query parameters or set defaults
$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-t');

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'pay') {
        $invoice_id = $_POST['invoice_id'] ?? 0;
        
        try {
            $db->exec('BEGIN TRANSACTION');
            
            // Debug log
            error_log("Starting payment process for invoice ID: " . $invoice_id);
            
            // Get invoice details and verify it's not already paid
            $stmt = $db->prepare('SELECT id, total_amount, status FROM invoices WHERE id = :id');
            $stmt->bindValue(':id', $invoice_id, SQLITE3_INTEGER);
            $result = $stmt->execute();
            $invoice = $result->fetchArray(SQLITE3_ASSOC);
            
            // Debug log
            error_log("Invoice details: " . print_r($invoice, true));
            
            if (!$invoice) {
                throw new Exception('الفاتورة غير موجودة');
            }
            
            if ($invoice['status'] === 'paid') {
                throw new Exception('هذه الفاتورة مسددة بالفعل');
            }
            
            // Get cash fund
            $stmt = $db->prepare('SELECT id, current_balance FROM cash_fund ORDER BY id DESC LIMIT 1');
            $result = $stmt->execute();
            $cash_fund = $result->fetchArray(SQLITE3_ASSOC);
            
            // Debug log
            error_log("Cash fund details: " . print_r($cash_fund, true));
            
            if (!$cash_fund) {
                throw new Exception('الرجاء إنشاء صندوق مالي أولاً');
            }
            
            // Update invoice status
            $stmt = $db->prepare('UPDATE invoices SET status = "paid", updated_at = CURRENT_TIMESTAMP WHERE id = :id');
            $stmt->bindValue(':id', $invoice_id, SQLITE3_INTEGER);
            $result = $stmt->execute();
            
            // Debug log
            error_log("Invoice status update result: " . ($result ? "success" : "failed"));
            
            // Update cash fund balance
            $new_balance = $cash_fund['current_balance'] + $invoice['total_amount'];
            $stmt = $db->prepare('UPDATE cash_fund SET current_balance = :balance, updated_at = CURRENT_TIMESTAMP WHERE id = :id');
            $stmt->bindValue(':balance', $new_balance, SQLITE3_FLOAT);
            $stmt->bindValue(':id', $cash_fund['id'], SQLITE3_INTEGER);
            $result = $stmt->execute();
            
            // Debug log
            error_log("Cash fund update result: " . ($result ? "success" : "failed") . ", New balance: " . $new_balance);
            
            // Record financial transaction
            $stmt = $db->prepare('
                INSERT INTO financial_transactions (
                    transaction_type,
                    amount,
                    source_type,
                    source_id,
                    description,
                    reference_type,
                    reference_id,
                    balance_after,
                    created_at
                ) VALUES (
                    "DEPOSIT",
                    :amount,
                    "CASH_FUND",
                    :cash_fund_id,
                    :description,
                    "INVOICE",
                    :invoice_id,
                    :balance_after,
                    CURRENT_TIMESTAMP
                )
            ');
            
            $stmt->bindValue(':amount', $invoice['total_amount'], SQLITE3_FLOAT);
            $stmt->bindValue(':cash_fund_id', $cash_fund['id'], SQLITE3_INTEGER);
            $stmt->bindValue(':description', "تسديد الفاتورة رقم " . $invoice_id, SQLITE3_TEXT);
            $stmt->bindValue(':invoice_id', $invoice_id, SQLITE3_INTEGER);
            $stmt->bindValue(':balance_after', $new_balance, SQLITE3_FLOAT);
            $result = $stmt->execute();
            
            // Debug log
            error_log("Financial transaction insert result: " . ($result ? "success" : "failed"));
            
            $db->exec('COMMIT');
            error_log("Transaction committed successfully");
            
            logActivity('تسديد فاتورة', "رقم الفاتورة: $invoice_id - المبلغ: " . number_format($invoice['total_amount'], 2) . " درهم");
            
            $_SESSION['success'] = 'تم تسديد الفاتورة وتحديث رصيد الصندوق بنجاح. المبلغ: ' . number_format($invoice['total_amount'], 2) . ' درهم';
            header('Location: invoices.php');
            exit;
            
        } catch (Exception $e) {
            $db->exec('ROLLBACK');
            error_log("Payment process failed: " . $e->getMessage());
            $_SESSION['error'] = 'حدث خطأ: ' . $e->getMessage();
            header('Location: invoices.php');
            exit;
        }
    }
}

// Calculate invoices when filter button is clicked
if (isset($_GET['start_date']) && isset($_GET['end_date'])) {
    $start_date = $_GET['start_date'];
    $end_date = $_GET['end_date'];
    
    try {
        $db->exec('BEGIN');
        
        // Get all consumption records for the period
        $stmt = $db->prepare('
            SELECT c.id as consumption_id, c.subscriber_id, c.previous_reading, c.current_reading, c.reading_date, s.family_members
            FROM consumption c
            JOIN subscribers s ON c.subscriber_id = s.id
            WHERE c.reading_date BETWEEN :start_date AND :end_date
            AND NOT EXISTS (SELECT 1 FROM invoices i WHERE i.consumption_id = c.id)
        ');
        $stmt->bindValue(':start_date', $start_date);
        $stmt->bindValue(':end_date', $end_date);
        $result = $stmt->execute();
        
        // Calculate and create invoices
        require_once 'includes/billing.php';
        $billing = new BillingCalculator($db);
        $created_count = 0;
        
        while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
            $invoice = $billing->calculateInvoice($row['consumption_id']);
            
            // Insert invoice
            $stmt2 = $db->prepare('
                INSERT INTO invoices (
                    consumption_id, subscriber_id, fixed_fees, 
                    collective_entitlement_amount, consumption_amount, 
                    penalties, total_amount
                ) VALUES (
                    :consumption_id, :subscriber_id, :fixed_fees,
                    :collective_entitlement_amount, :consumption_amount,
                    :penalties, :total_amount
                )
            ');
            $stmt2->bindValue(':consumption_id', $invoice['consumption_id'], SQLITE3_INTEGER);
            $stmt2->bindValue(':subscriber_id', $invoice['subscriber_id'], SQLITE3_INTEGER);
            $stmt2->bindValue(':fixed_fees', $invoice['fixed_fees'], SQLITE3_FLOAT);
            $stmt2->bindValue(':collective_entitlement_amount', $invoice['collective_entitlement_amount'], SQLITE3_FLOAT);
            $stmt2->bindValue(':consumption_amount', $invoice['consumption_amount'], SQLITE3_FLOAT);
            $stmt2->bindValue(':penalties', $invoice['penalties'], SQLITE3_FLOAT);
            $stmt2->bindValue(':total_amount', $invoice['total_amount'], SQLITE3_FLOAT);
            $stmt2->execute();
            
            $created_count++;
        }
        
        $db->exec('COMMIT');
        
        if ($created_count > 0) {
            $_SESSION['success'] = "تم إنشاء $created_count فاتورة جديدة";
        }
    } catch (Exception $e) {
        $db->exec('ROLLBACK');
        $_SESSION['error'] = 'حدث خطأ أثناء إنشاء الفواتير: ' . $e->getMessage();
    }
}

// Get invoices with subscriber details
$invoices_query = '
    SELECT 
        i.id,
        i.consumption_id,
        s.meter_number,
        s.full_name,
        s.family_members,
        c.previous_reading,
        c.current_reading,
        (c.current_reading - c.previous_reading) as consumption,
        i.fixed_fees,
        i.collective_entitlement_amount,
        i.consumption_amount,
        i.penalties,
        i.total_amount,
        c.reading_date,
        i.status,
        i.created_at
    FROM invoices i
    JOIN consumption c ON i.consumption_id = c.id
    JOIN subscribers s ON i.subscriber_id = s.id
    WHERE 1=1
';

if (!empty($start_date)) {
    $invoices_query .= ' AND c.reading_date >= :start_date';
}
if (!empty($end_date)) {
    $invoices_query .= ' AND c.reading_date <= :end_date';
}

$invoices_query .= ' ORDER BY c.reading_date DESC';
$stmt = $db->prepare($invoices_query);
$stmt->bindValue(':start_date', $start_date);
$stmt->bindValue(':end_date', $end_date);
$result = $stmt->execute();
$invoices = [];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    $invoices[] = $row;
}

// Calculate summary statistics
$total_amount = array_sum(array_column($invoices, 'total_amount'));
$total_paid = array_sum(array_map(function($invoice) {
    return $invoice['status'] === 'paid' ? $invoice['total_amount'] : 0;
}, $invoices));
$total_unpaid = array_sum(array_map(function($invoice) {
    return $invoice['status'] !== 'paid' ? $invoice['total_amount'] : 0;
}, $invoices));
$total_consumption = array_sum(array_map(function($invoice) {
    return $invoice['current_reading'] - $invoice['previous_reading'];
}, $invoices));

?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة الفواتير</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css" rel="stylesheet">
    <style>
        @media print {
            .no-print {
                display: none !important;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <?php include 'includes/sidebar.php'; ?>

            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom no-print">
                    <h1 class="h2">إدارة الفواتير</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="btn-group me-2">
                            <form id="printForm" action="print_invoices.php" method="GET" class="d-flex align-items-center">
                                <input type="hidden" name="start_date" value="<?php echo htmlspecialchars($start_date); ?>">
                                <input type="hidden" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>">
                                <input type="hidden" name="selected_invoices" id="selectedInvoices" value="">
                                <button type="submit" class="btn btn-primary me-2" id="printSelected" disabled>
                                    طباعة المحدد
                                </button>
                            </form>
                        </div>
                    </div>
                </div>

                <?php if (isset($_SESSION['error'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($_SESSION['error']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php unset($_SESSION['error']); ?>
                <?php endif; ?>

                <?php if (isset($_SESSION['success'])): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($_SESSION['success']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php unset($_SESSION['success']); ?>
                <?php endif; ?>

                <div class="row g-3 mb-4">
                    <div class="col-sm-6 col-md-3">
                        <div class="card bg-primary text-white h-100">
                            <div class="card-body">
                                <h6 class="card-title">مجموع الفواتير</h6>
                                <p class="card-text display-6" id="totalAmount"><?php echo number_format($total_amount, 2); ?> درهم</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-md-3">
                        <div class="card bg-success text-white h-100">
                            <div class="card-body">
                                <h6 class="card-title">المبالغ المؤداة</h6>
                                <p class="card-text display-6" id="totalPaid"><?php echo number_format($total_paid, 2); ?> درهم</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-md-3">
                        <div class="card bg-warning text-dark h-100">
                            <div class="card-body">
                                <h6 class="card-title">المبالغ غير المؤداة</h6>
                                <p class="card-text display-6" id="totalUnpaid"><?php echo number_format($total_unpaid, 2); ?> درهم</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-md-3">
                        <div class="card bg-info text-white h-100">
                            <div class="card-body">
                                <h6 class="card-title">مجموع الاستهلاك</h6>
                                <p class="card-text display-6" id="totalConsumption"><?php echo number_format($total_consumption, 1); ?> م³</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Date Filter Form -->
                <form method="GET" class="row g-3 mb-4 no-print">
                    <div class="col-md-4">
                        <label for="start_date" class="form-label">من تاريخ</label>
                        <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo htmlspecialchars($start_date); ?>">
                    </div>
                    <div class="col-md-4">
                        <label for="end_date" class="form-label">إلى تاريخ</label>
                        <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">&nbsp;</label>
                        <button type="submit" class="btn btn-primary d-block">تصفية</button>
                    </div>
                </form>

                <div class="table-responsive">
                    <table class="table table-striped table-hover" id="invoicesTable">
                        <thead>
                            <tr>
                                <th>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="selectAll">
                                    </div>
                                </th>
                                <th>رقم العداد</th>
                                <th>اسم المشترك</th>
                                <th>عدد أفراد الأسرة</th>
                                <th>القراءة السابقة</th>
                                <th>القراءة الحالية</th>
                                <th>الاستهلاك</th>
                                <th>المصاريف الثابتة</th>
                                <th>مبلغ الاستحقاق الجماعي</th>
                                <th>مبلغ الاستهلاك</th>
                                <th>الغرامات</th>
                                <th>المجموع</th>
                                <th>تاريخ القراءة</th>
                                <th>تاريخ الاستحقاق</th>
                                <th>الحالة</th>
                                <th class="no-print">إجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($invoices as $invoice): ?>
                                <tr>
                                    <td>
                                        <div class="form-check">
                                            <input class="form-check-input invoice-checkbox" type="checkbox" value="<?php echo $invoice['id']; ?>">
                                        </div>
                                    </td>
                                    <td><?php echo htmlspecialchars($invoice['meter_number']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['full_name']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['family_members']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['previous_reading']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['current_reading']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['consumption']); ?></td>
                                    <td><?php echo number_format($invoice['fixed_fees'], 2); ?></td>
                                    <td><?php echo number_format($invoice['collective_entitlement_amount'], 2); ?></td>
                                    <td><?php echo number_format($invoice['consumption_amount'], 2); ?></td>
                                    <td><?php echo number_format($invoice['penalties'], 2); ?></td>
                                    <td class="fw-bold"><?php echo number_format($invoice['total_amount'], 2); ?></td>
                                    <td><?php echo date('Y-m-d', strtotime($invoice['reading_date'])); ?></td>
                                    <td><?php echo date('Y-m-d', strtotime($invoice['created_at'])); ?></td>
                                    <td>
                                        <span class="badge <?php echo $invoice['status'] === 'paid' ? 'bg-success' : 'bg-warning'; ?>">
                                            <?php echo $invoice['status'] === 'paid' ? 'مسددة' : 'غير مسددة'; ?>
                                        </span>
                                    </td>
                                    <td class="no-print">
                                        <?php if ($invoice['status'] !== 'paid'): ?>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('هل أنت متأكد من تسديد هذه الفاتورة؟');">
                                                <input type="hidden" name="action" value="pay">
                                                <input type="hidden" name="invoice_id" value="<?php echo $invoice['id']; ?>">
                                                <button type="submit" class="btn btn-success btn-sm">
                                                    تسديد
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                      
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                          
                        </tfoot>
                    </table>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function() {
            // Initialize DataTable
            var table = $('#invoicesTable').DataTable({
                "order": [[2, "desc"]],
                "language": {
                    "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/Arabic.json"
                }
            });

            // Handle invoice payment
            $('.pay-invoice').on('click', function(e) {
                e.preventDefault();
                const invoiceId = $(this).data('id');
                const row = $(this).closest('tr');
                
                if (confirm('هل أنت متأكد من تسديد هذه الفاتورة؟')) {
                    $.ajax({
                        url: 'ajax/update_invoice.php',
                        method: 'POST',
                        data: {
                            invoice_id: invoiceId,
                            start_date: '<?php echo $start_date; ?>',
                            end_date: '<?php echo $end_date; ?>'
                        },
                        success: function(response) {
                            if (response.success) {
                                // Update invoice row
                                const invoice = response.data.invoice;
                                row.find('.status-cell').html('<span class="badge bg-success">مؤداة</span>');
                                row.find('.actions-cell').html('-');
                                
                                // Update summary cards
                                const summary = response.data.summary;
                                $('#totalAmount').text(Number(summary.total_amount).toFixed(2) + ' درهم');
                                $('#totalPaid').text(Number(summary.total_paid).toFixed(2) + ' درهم');
                                $('#totalUnpaid').text(Number(summary.total_unpaid).toFixed(2) + ' درهم');
                                $('#totalConsumption').text(Number(summary.total_consumption).toFixed(1) + ' م³');
                                
                                // Show success message
                                alert('تم تسديد الفاتورة بنجاح');
                            } else {
                                alert(response.message || 'حدث خطأ أثناء تحديث حالة الفاتورة');
                            }
                        },
                        error: function() {
                            alert('حدث خطأ في الاتصال بالخادم');
                        }
                    });
                }
            });

            // Handle checkbox selection
            var selectedIds = [];
            $('.invoice-checkbox').change(function() {
                selectedIds = $('.invoice-checkbox:checked').map(function() {
                    return $(this).val();
                }).get();
                
                $('#selectedInvoices').val(selectedIds.join(','));
                $('#printSelected').prop('disabled', selectedIds.length === 0);
            });

            // Handle select all checkbox
            $('#selectAll').change(function() {
                $('.invoice-checkbox').prop('checked', $(this).prop('checked')).trigger('change');
            });
        });
    </script>
</body>
</html>
