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

$db = getDB();
$success = isset($_GET['success']) ? $_GET['success'] : null;
$error = null;

// Handle deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['subscriber_id'])) {
        $subscriber_id = filter_var($_POST['subscriber_id'], FILTER_VALIDATE_INT);
        
        if ($subscriber_id === false) {
            $error = 'معرف المشترك غير صالح';
        } else {
            try {
                $db->exec('BEGIN TRANSACTION');
                
                // Get subscriber info for logging
                $stmt = $db->prepare('SELECT meter_number, full_name FROM subscribers WHERE id = :id AND status = 1');
                $stmt->bindValue(':id', $subscriber_id, SQLITE3_INTEGER);
                $subscriber = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
                
                if (!$subscriber) {
                    throw new Exception('لم يتم العثور على المشترك المحدد أو تم حذفه مسبقاً');
                }
                
                // Delete related records in correct order
                // First delete invoices related to consumption records
                $stmt = $db->prepare("DELETE FROM invoices WHERE consumption_id IN (SELECT id FROM consumption WHERE subscriber_id = :id)");
                $stmt->bindValue(':id', $subscriber_id, SQLITE3_INTEGER);
                $stmt->execute();
                
                // Then delete consumption records
                $stmt = $db->prepare("DELETE FROM consumption WHERE subscriber_id = :id");
                $stmt->bindValue(':id', $subscriber_id, SQLITE3_INTEGER);
                $stmt->execute();
                
                // Finally delete the subscriber
                $stmt = $db->prepare("DELETE FROM subscribers WHERE id = :id");
                $stmt->bindValue(':id', $subscriber_id, SQLITE3_INTEGER);
                $stmt->execute();
                
                if ($db->changes() === 0) {
                    throw new Exception('فشل حذف المشترك');
                }
                
                // Log the deletion
                logActivity('حذف مشترك', sprintf("رقم العداد: %s، اسم المشترك: %s", 
                    $subscriber['meter_number'],
                    $subscriber['full_name']
                ));
                
                $db->exec('COMMIT');
                header('Location: delete_subscriber.php?success=1');
                exit;
                
            } catch (Exception $e) {
                $db->exec('ROLLBACK');
                error_log('Error deleting subscriber: ' . $e->getMessage());
                $error = 'حدث خطأ أثناء حذف المشترك: ' . $e->getMessage();
            }
        }
    } elseif (isset($_POST['delete_all']) && $_POST['delete_all'] === 'confirm') {
        try {
            $db->exec('BEGIN TRANSACTION');
            
            // Get count of subscribers for logging
            $count = $db->querySingle('SELECT COUNT(*) FROM subscribers WHERE status = 1');
            
            if ($count === 0) {
                throw new Exception('لا يوجد مشتركين للحذف');
            }
            
            // Delete all records in correct order
            $db->exec('DELETE FROM invoices WHERE consumption_id IN (SELECT id FROM consumption WHERE subscriber_id IN (SELECT id FROM subscribers WHERE status = 1))');
            $db->exec('DELETE FROM consumption WHERE subscriber_id IN (SELECT id FROM subscribers WHERE status = 1)');
            $db->exec('DELETE FROM subscribers WHERE status = 1');
            
            // Log the mass deletion
            logActivity('حذف جميع المشتركين', "تم حذف $count مشترك");
            
            $db->exec('COMMIT');
            header('Location: delete_subscriber.php?success=1');
            exit;
            
        } catch (Exception $e) {
            $db->exec('ROLLBACK');
            error_log('Error deleting all subscribers: ' . $e->getMessage());
            $error = 'حدث خطأ أثناء حذف جميع المشتركين: ' . $e->getMessage();
        }
    }
}

// Get subscribers with their latest consumption and invoice
$query = "SELECT 
    s.*,
    c.reading_date as last_reading_date,
    c.current_reading as last_reading,
    i.total_amount as last_invoice_amount,
    i.id as last_invoice_id,
    i.status as invoice_status,
    (SELECT COUNT(*) FROM consumption WHERE subscriber_id = s.id) as readings_count,
    (SELECT COUNT(*) FROM invoices WHERE consumption_id IN (SELECT id FROM consumption WHERE subscriber_id = s.id)) as invoices_count
FROM subscribers s
LEFT JOIN (
    SELECT c1.* FROM consumption c1
    INNER JOIN (
        SELECT subscriber_id, MAX(reading_date) as max_date
        FROM consumption
        GROUP BY subscriber_id
    ) c2 ON c1.subscriber_id = c2.subscriber_id AND c1.reading_date = c2.max_date
) c ON s.id = c.subscriber_id
LEFT JOIN invoices i ON c.id = i.consumption_id
WHERE s.status = 1
ORDER BY CAST(s.meter_number AS INTEGER)";

$result = $db->query($query);
?>
<!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.3.2/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .table th {
            background-color: #f8f9fa;
            white-space: nowrap;
        }
        /* Dashboard styles */
        .sidebar {
            position: fixed;
            top: 0;
            right: 0;
            bottom: 0;
            z-index: 100;
            padding: 4px;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
        }
        .sidebar-sticky {
            position: relative;
            top: 0;
            height: calc(100vh - 48px);
            padding-top: .5rem;
            overflow-x: hidden;
            overflow-y: auto;
        }
        .navbar {
            box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .1);
        }
        @media (max-width: 767.98px) {
            .sidebar {
                top: 5rem;
            }
        }
    </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">
                    <h1 class="h2">حذف المشتركين</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteAllModal">
                            حذف جميع المشتركين
                        </button>
                    </div>
                </div>

                <?php if ($success): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        تم حذف المشترك بنجاح
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <?php if ($error): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo $error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <div class="table-responsive">
                    <table class="table table-striped table-hover align-middle">
                        <thead class="table-light">
                            <tr>
                                <th>رقم العداد</th>
                                <th>اسم المشترك</th>
                                <th>رقم الهاتف</th>
                                <th>تاريخ آخر قراءة</th>
                                <th>آخر قراءة</th>
                                <th>رقم آخر فاتورة</th>
                                <th>قيمة آخر فاتورة</th>
                                <th>حالة الدفع</th>
                                <th>الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($row = $result->fetchArray(SQLITE3_ASSOC)): ?>
                                <tr>
                                    <td class="fw-bold"><?php echo htmlspecialchars($row['meter_number']); ?></td>
                                    <td><?php echo htmlspecialchars($row['full_name']); ?></td>
                                    <td><?php echo htmlspecialchars($row['phone']); ?></td>
                                    <td><?php echo $row['last_reading_date'] ? date('Y-m-d', strtotime($row['last_reading_date'])) : '-'; ?></td>
                                    <td><?php echo $row['last_reading'] ? number_format($row['last_reading'], 2) : '-'; ?></td>
                                    <td><?php echo $row['last_invoice_id'] ?: '-'; ?></td>
                                    <td><?php echo $row['last_invoice_amount'] ? number_format($row['last_invoice_amount'], 2) : '-'; ?></td>
                                    <td>
                                        <?php if ($row['last_invoice_id']): ?>
                                            <?php if ($row['invoice_status'] == 1): ?>
                                                <span class="badge bg-success">مدفوعة</span>
                                            <?php else: ?>
                                                <span class="badge bg-danger">غير مدفوعة</span>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            -
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-danger btn-sm"
                                                data-bs-toggle="modal"
                                                data-bs-target="#deleteSubscriberModal"
                                                data-subscriber-id="<?php echo $row['id']; ?>"
                                                data-subscriber-name="<?php echo htmlspecialchars($row['full_name']); ?>"
                                                data-meter-number="<?php echo htmlspecialchars($row['meter_number']); ?>">
                                            <i class="bi bi-trash"></i>
                                            حذف المشترك
                                        </button>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </main>
        </div>
    </div>

    <!-- Delete Subscriber Modal -->
    <div class="modal fade" id="deleteSubscriberModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">تأكيد حذف المشترك</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="subscriber_id" id="subscriberIdInput">
                        
                        <div class="alert alert-warning">
                            <h6 class="alert-heading mb-1">تحذير!</h6>
                            <p class="mb-1">سيتم حذف المشترك التالي وجميع بياناته:</p>
                            <p class="mb-0" id="subscriberInfo"></p>
                        </div>
                        
                        <p class="text-danger">
                            <i class="bi bi-exclamation-triangle-fill"></i>
                            هذا الإجراء لا يمكن التراجع عنه. سيتم حذف جميع القراءات والفواتير المرتبطة بهذا المشترك.
                        </p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                        <button type="submit" class="btn btn-danger">تأكيد الحذف</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Delete All Modal -->
    <div class="modal fade" id="deleteAllModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">تأكيد حذف جميع المشتركين</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-danger">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        <strong>تحذير!</strong> هذا الإجراء لا يمكن التراجع عنه.
                    </div>
                    <p>هل أنت متأكد من حذف جميع المشتركين؟ سيتم حذف:</p>
                    <ul>
                        <li>جميع المشتركين</li>
                        <li>جميع قراءات العدادات</li>
                        <li>جميع الفواتير المرتبطة</li>
                    </ul>
                    <p>اكتب "تأكيد" في الحقل أدناه للمتابعة:</p>
                    <input type="text" id="deleteAllConfirmation" class="form-control" placeholder="اكتب 'تأكيد'">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <form method="POST" style="display: inline;">
                        <input type="hidden" name="delete_all" value="confirm">
                        <button type="submit" class="btn btn-danger" id="confirmDeleteAll" disabled>
                            حذف الكل
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const deleteSubscriberModal = document.getElementById('deleteSubscriberModal');
            
            deleteSubscriberModal.addEventListener('show.bs.modal', function(event) {
                const button = event.relatedTarget;
                const subscriberId = button.getAttribute('data-subscriber-id');
                const subscriberName = button.getAttribute('data-subscriber-name');
                const meterNumber = button.getAttribute('data-meter-number');
                
                document.getElementById('subscriberIdInput').value = subscriberId;
                document.getElementById('subscriberInfo').textContent = 
                    `${subscriberName} (رقم العداد: ${meterNumber})`;
            });
        });
    </script>
    <script>
        // Enable delete all button only when confirmation text is correct
        document.getElementById('deleteAllConfirmation').addEventListener('input', function() {
            document.getElementById('confirmDeleteAll').disabled = this.value !== 'تأكيد';
        });
    </script>
</body>
</html>
