<?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 and payment date
            $stmt = $db->prepare('UPDATE invoices SET status = "paid", payment_date = CURRENT_TIMESTAMP, 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');
            logActivity('تسديد فاتورة', "تم تسديد الفاتورة رقم $invoice_id");
            
            // Return success response with invoice ID for receipt printing
            header('Content-Type: application/json');
            echo json_encode(['success' => true, 'message' => 'تم تسديد الفاتورة بنجاح', 'invoice_id' => $invoice_id]);
            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.payment_date,
        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">
                        <form id="printForm" action="print_invoices.php" method="GET" target="_blank" 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>
                                <i class="bi bi-printer"></i> طباعة المحدد
                            </button>
                        </form>
                    </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 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['previous_reading']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['current_reading']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['current_reading'] - $invoice['previous_reading']); ?></td>
                                    <td><?php echo number_format($invoice['fixed_fees'], 2); ?></td>
                                    <td><?php echo number_format($invoice['consumption_amount'], 2); ?></td>
                                    <td><?php echo number_format($invoice['penalties'], 2); ?></td>
                                    <td><?php echo number_format($invoice['total_amount'], 2); ?></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 pay-invoice-form">
                                                <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">
                                                    <i class="bi bi-check-circle"></i> تسديد
                                                </button>
                                            </form>
                                        <?php else: ?>
                                            <button type="button" class="btn btn-primary btn-sm print-receipt" data-invoice-id="<?php echo $invoice['id']; ?>">
                                                <i class="bi bi-printer"></i> reçu 
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </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() {
            // DataTables initialization
            $('#invoicesTable').DataTable({
                "order": [[1, "desc"]], // Order by second column (meter number) instead of checkbox column
                "language": {
                    "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/ar.json"
                }
            });

            // Handle invoice payment
            $('.pay-invoice-form').on('submit', function(e) {
                e.preventDefault();
                const form = $(this);
                
                $.ajax({
                    url: 'invoices.php',
                    method: 'POST',
                    data: form.serialize(),
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            // Show success message
                            alert(response.message);
                            
                            // Open receipt in new window
                            window.open('print_receipt.php?invoice_id=' + response.invoice_id, '_blank', 'width=800,height=600');
                            
                            // Reload page to update status
                            location.reload();
                        } else {
                            alert('حدث خطأ: ' + response.message);
                        }
                    },
                    error: function() {
                        alert('حدث خطأ أثناء معالجة الطلب');
                    }
                });
            });

            // Handle receipt printing for already paid invoices
            $('.print-receipt').on('click', function() {
                const invoiceId = $(this).data('invoice-id');
                window.open('print_receipt.php?invoice_id=' + invoiceId, '_blank', 'width=800,height=600');
            });

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

            // Handle individual checkbox changes
            $('.invoice-checkbox').on('change', function() {
                updateSelectedInvoices();
            });

            // Handle select all checkbox
            $('#selectAll').on('change', function() {
                $('.invoice-checkbox').prop('checked', $(this).prop('checked'));
                updateSelectedInvoices();
            });

            // Update "Select All" state when individual checkboxes change
            $('.invoice-checkbox').on('change', function() {
                const totalCheckboxes = $('.invoice-checkbox').length;
                const checkedCheckboxes = $('.invoice-checkbox:checked').length;
                $('#selectAll').prop('checked', totalCheckboxes === checkedCheckboxes);
                updateSelectedInvoices();
            });

            // Handle print form submission
            $('#printForm').on('submit', function(e) {
                const selectedIds = $('#selectedInvoices').val();
                if (!selectedIds) {
                    e.preventDefault();
                    alert('الرجاء تحديد الفواتير المراد طباعتها');
                    return false;
                }
                return true;
            });
        });
    </script>
</body>
</html>
