<?php
// --- Companies Logic ---
$search_name = $_GET['name'] ?? '';
$search_phone = $_GET['phone'] ?? '';
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$where = "WHERE 1=1";
$params = [];

if ($search_name) {
    $where .= " AND (name_en LIKE ? OR name_ar LIKE ?)";
    $params[] = "%$search_name%";
    $params[] = "%$search_name%";
}
if ($search_phone) {
    $where .= " AND phone LIKE ?";
    $params[] = "%$search_phone%";
}

// Count Total Companies
$countQuery = "SELECT COUNT(*) FROM insurance_companies $where";
$stmt = $db->prepare($countQuery);
$stmt->execute($params);
$totalInsurance = $stmt->fetchColumn();
$totalPages = ceil($totalInsurance / $limit);

// Fetch Companies
$query = "SELECT * FROM insurance_companies $where ORDER BY id DESC LIMIT $limit OFFSET $offset";
$stmt = $db->prepare($query);
$stmt->execute($params);
$insurance_companies = $stmt->fetchAll();


// --- Transactions Logic ---
$trans_page = isset($_GET['trans_page']) && is_numeric($_GET['trans_page']) ? (int)$_GET['trans_page'] : 1;
$trans_limit = 10;
$trans_offset = ($trans_page - 1) * $trans_limit;

$trans_where = "WHERE 1=1";
$trans_params = [];

$trans_company_id = $_GET['trans_company_id'] ?? '';
$trans_start_date = $_GET['trans_start_date'] ?? '';
$trans_end_date = $_GET['trans_end_date'] ?? '';

if ($trans_company_id) {
    $trans_where .= " AND t.insurance_company_id = ?";
    $trans_params[] = $trans_company_id;
}
if ($trans_start_date) {
    $trans_where .= " AND t.payment_date >= ?";
    $trans_params[] = $trans_start_date;
}
if ($trans_end_date) {
    $trans_where .= " AND t.payment_date <= ?";
    $trans_params[] = $trans_end_date;
}

// Count Transactions
$countTransQuery = "SELECT COUNT(*) FROM insurance_payments t $trans_where";
$stmt = $db->prepare($countTransQuery);
$stmt->execute($trans_params);
$totalTrans = $stmt->fetchColumn();
$totalTransPages = ceil($totalTrans / $trans_limit);

// Fetch Transactions
$transQuery = "SELECT t.*, c.name_$lang as company_name 
               FROM insurance_payments t 
               LEFT JOIN insurance_companies c ON t.insurance_company_id = c.id 
               $trans_where 
               ORDER BY t.payment_date DESC, t.id DESC 
               LIMIT $trans_limit OFFSET $trans_offset";
$stmt = $db->prepare($transQuery);
$stmt->execute($trans_params);
$transactions = $stmt->fetchAll();


// --- AJAX HANDLER ---
if (isset($_GET['ajax_search'])) {
    header('Content-Type: application/json');
    ob_start();
    
    if (isset($_GET['tab']) && $_GET['tab'] === 'transactions') {
        if (empty($transactions)): ?>
        <tr>
            <td colspan="8" class="text-center py-5 text-muted">
                <i class="bi bi-cash-stack display-4 d-block mb-3"></i>
                <?php echo __('no_transactions_found'); ?>
            </td>
        </tr>
        <?php else: ?>
        <?php foreach ($transactions as $t): ?>
        <tr>
            <td class="px-4 text-secondary">#<?php echo $t['id']; ?></td>
            <td class="fw-semibold text-dark"><?php echo date('Y-m-d', strtotime($t['payment_date'])); ?></td>
            <td class="text-secondary"><?php echo htmlspecialchars($t['company_name']); ?></td>
            <td class="text-dark fw-bold"><?php echo format_currency($t['amount']); ?></td>
            <td class="text-secondary"><?php echo htmlspecialchars($t['reference_number'] ?: '-'); ?></td>
            <td class="text-secondary">
                <?php 
                $method_key = 'payment_method_' . strtolower(str_replace(' ', '_', $t['payment_method']));
                echo __($method_key) !== $method_key ? __($method_key) : $t['payment_method']; 
                ?>
            </td>
            <td class="text-muted small text-truncate" style="max-width: 150px;" title="<?php echo htmlspecialchars($t['notes']); ?>">
                <?php echo htmlspecialchars($t['notes'] ?: '-'); ?>
            </td>
            <td class="text-end px-4">
                <button class="btn btn-sm btn-light text-primary me-1" 
                        onclick='openEditTransactionModal(<?php echo json_encode($t); ?>)'
                        title="<?php echo __('edit'); ?>">
                    <i class="bi bi-pencil"></i>
                </button>
                <button class="btn btn-sm btn-light text-danger" 
                        onclick="deleteTransaction(<?php echo $t['id']; ?>)"
                        title="<?php echo __('delete'); ?>">
                    <i class="bi bi-trash"></i>
                </button>
            </td>
        </tr>
        <?php endforeach; ?>
        <?php endif; 
        $table_html = ob_get_clean();

        ob_start();
        if ($totalTransPages > 1): ?>
        <div class="d-flex justify-content-between align-items-center p-3 border-top">
            <div class="text-muted small">
                <?php echo __('showing'); ?> <?php echo $trans_offset + 1; ?> - <?php echo min($trans_offset + $trans_limit, $totalTrans); ?> <?php echo __('of'); ?> <?php echo $totalTrans; ?>
            </div>
            <nav aria-label="Page navigation">
                <ul class="pagination pagination-sm mb-0">
                    <li class="page-item <?php echo $trans_page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="#" data-page="<?php echo $trans_page - 1; ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    <?php
                    $range = 2;
                    $pages_to_show = [];
                    $pages_to_show[] = 1;
                    if ($totalTransPages > 1) { $pages_to_show[] = $totalTransPages; }
                    for ($i = $trans_page - $range; $i <= $trans_page + $range; $i++) {
                        if ($i > 1 && $i < $totalTransPages) { $pages_to_show[] = $i; }
                    }
                    $pages_to_show = array_unique($pages_to_show);
                    sort($pages_to_show);
                    
                    $prev_page = 0;
                    foreach ($pages_to_show as $p):
                        if ($prev_page > 0 && $p > $prev_page + 1): ?>
                            <li class="page-item disabled"><span class="page-link">...</span></li>
                        <?php endif; ?>
                        <li class="page-item <?php echo $trans_page == $p ? 'active' : ''; ?>">
                            <a class="page-link" href="#" data-page="<?php echo $p; ?>">
                                <?php echo $p; ?>
                            </a>
                        </li>
                        <?php 
                        $prev_page = $p;
                    endforeach; 
                    ?>
                    <li class="page-item <?php echo $trans_page >= $totalTransPages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="#" data-page="<?php echo $trans_page + 1; ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
        <?php endif; 
        $pagination_html = ob_get_clean();
        
        echo json_encode(['html' => $table_html, 'pagination' => $pagination_html]);

    } else {
        // Companies Tab
        if (empty($insurance_companies)): ?>
        <tr>
            <td colspan="7" class="text-center py-5 text-muted">
                <i class="bi bi-shield-check display-4 d-block mb-3"></i>
                <?php echo __('no_insurance_companies_found'); ?>
            </td>
        </tr>
        <?php else: ?>
        <?php foreach ($insurance_companies as $ic): ?>
        <tr>
            <td class="px-4 text-secondary">#<?php echo $ic['id']; ?></td>
            <td class="fw-semibold text-dark"><?php echo htmlspecialchars($ic['name_en']); ?></td>
            <td class="text-secondary"><?php echo htmlspecialchars($ic['name_ar']); ?></td>
            <td class="text-secondary"><?php echo htmlspecialchars($ic['email'] ?: '-'); ?></td>
            <td class="text-secondary"><?php echo htmlspecialchars($ic['phone'] ?: '-'); ?></td>
            <td class="text-muted"><?php echo date('Y-m-d', strtotime($ic['created_at'])); ?></td>
            <td class="text-end px-4">
                <div class="dropdown">
                    <button class="btn btn-sm btn-light text-secondary" type="button" data-bs-toggle="dropdown">
                        <i class="bi bi-three-dots-vertical"></i>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end border-0 shadow-sm">
                        <li>
                            <a class="dropdown-item" href="#" onclick="openStatementModal(<?php echo $ic['id']; ?>)">
                                <i class="bi bi-printer me-2"></i> <?php echo __('statement'); ?>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item" href="#" onclick='openEditInsuranceModal(<?php echo json_encode($ic); ?>)'>
                                <i class="bi bi-pencil me-2"></i> <?php echo __('edit'); ?>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <li>
                            <a class="dropdown-item text-danger" href="#" onclick="deleteInsurance(<?php echo $ic['id']; ?>)">
                                <i class="bi bi-trash me-2"></i> <?php echo __('delete'); ?>
                            </a>
                        </li>
                    </ul>
                </div>
            </td>
        </tr>
        <?php endforeach; ?>
        <?php endif; 
        $table_html = ob_get_clean();

        ob_start();
        if ($totalPages > 1): ?>
        <div class="d-flex justify-content-between align-items-center p-3 border-top">
            <div class="text-muted small">
                <?php echo __('showing'); ?> <?php echo $offset + 1; ?> - <?php echo min($offset + $limit, $totalInsurance); ?> <?php echo __('of'); ?> <?php echo $totalInsurance; ?>
            </div>
            <nav aria-label="Page navigation">
                <ul class="pagination pagination-sm mb-0">
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="#" data-page="<?php echo $page - 1; ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    <?php
                    $range = 2;
                    $pages_to_show = [];
                    $pages_to_show[] = 1;
                    if ($totalPages > 1) { $pages_to_show[] = $totalPages; }
                    for ($i = $page - $range; $i <= $page + $range; $i++) {
                        if ($i > 1 && $i < $totalPages) { $pages_to_show[] = $i; }
                    }
                    $pages_to_show = array_unique($pages_to_show);
                    sort($pages_to_show);
                    
                    $prev_page = 0;
                    foreach ($pages_to_show as $p):
                        if ($prev_page > 0 && $p > $prev_page + 1): ?>
                            <li class="page-item disabled"><span class="page-link">...</span></li>
                        <?php endif; ?>
                        <li class="page-item <?php echo $page == $p ? 'active' : ''; ?>">
                            <a class="page-link" href="#" data-page="<?php echo $p; ?>">
                                <?php echo $p; ?>
                            </a>
                        </li>
                        <?php 
                        $prev_page = $p;
                    endforeach; 
                    ?>
                    <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="#" data-page="<?php echo $page + 1; ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
        <?php endif; 
        $pagination_html = ob_get_clean();
        
        echo json_encode(['html' => $table_html, 'pagination' => $pagination_html]);
    }
    exit;
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h3 class="fw-bold text-secondary"><?php echo __('insurance'); ?></h3>
    <div>
        <button class="btn btn-outline-primary shadow-sm me-2" data-bs-toggle="modal" data-bs-target="#addTransactionModal">
            <i class="bi bi-plus-lg me-1"></i> <?php echo __('add_transaction'); ?>
        </button>
        <button class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#addInsuranceModal">
            <i class="bi bi-plus-lg me-1"></i> <?php echo __('add_insurance'); ?>
        </button>
    </div>
</div>

<ul class="nav nav-tabs mb-4" id="insuranceTabs" role="tablist">
    <li class="nav-item" role="presentation">
        <button class="nav-link active" id="companies-tab" data-bs-toggle="tab" data-bs-target="#companies" type="button" role="tab" aria-controls="companies" aria-selected="true"><?php echo __('companies'); ?></button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" id="transactions-tab" data-bs-toggle="tab" data-bs-target="#transactions" type="button" role="tab" aria-controls="transactions" aria-selected="false"><?php echo __('transactions'); ?></button>
    </li>
</ul>

<div class="tab-content" id="insuranceTabsContent">
    
    <!-- COMPANIES TAB -->
    <div class="tab-pane fade show active" id="companies" role="tabpanel" aria-labelledby="companies-tab">
        
        <!-- Search Bar -->
        <div class="card shadow-sm border-0 mb-4">
            <div class="card-body">
                <form id="insuranceSearchForm" class="row g-3" onsubmit="return false;">
                    <div class="col-md-5">
                        <div class="input-group">
                            <span class="input-group-text bg-light border-end-0 text-muted"><i class="bi bi-search"></i></span>
                            <input type="text" name="name" id="insSearchName" class="form-control bg-light border-start-0" placeholder="<?php echo __('name'); ?>" value="<?php echo htmlspecialchars($search_name); ?>">
                        </div>
                    </div>
                    <div class="col-md-5">
                        <div class="input-group">
                            <span class="input-group-text bg-light border-end-0 text-muted"><i class="bi bi-telephone"></i></span>
                            <input type="text" name="phone" id="insSearchPhone" class="form-control bg-light border-start-0" placeholder="<?php echo __('phone'); ?>" value="<?php echo htmlspecialchars($search_phone); ?>">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-secondary w-100" onclick="fetchInsurance(1)"><?php echo __('search'); ?></button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card shadow-sm border-0">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light text-secondary">
                            <tr>
                                <th class="px-4 py-3">ID</th>
                                <th class="py-3"><?php echo __('name_en'); ?></th>
                                <th class="py-3"><?php echo __('name_ar'); ?></th>
                                <th class="py-3"><?php echo __('email'); ?></th>
                                <th class="py-3"><?php echo __('phone'); ?></th>
                                <th class="py-3"><?php echo __('date'); ?></th>
                                <th class="py-3 text-end px-4"><?php echo __('actions'); ?></th>
                            </tr>
                        </thead>
                        <tbody id="insuranceTableBody">
                            <?php if (empty($insurance_companies)): ?>
                            <tr>
                                <td colspan="7" class="text-center py-5 text-muted">
                                    <i class="bi bi-shield-check display-4 d-block mb-3"></i>
                                    <?php echo __('no_insurance_companies_found'); ?>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($insurance_companies as $ic): ?>
                            <tr>
                                <td class="px-4 text-secondary">#<?php echo $ic['id']; ?></td>
                                <td class="fw-semibold text-dark"><?php echo htmlspecialchars($ic['name_en']); ?></td>
                                <td class="text-secondary"><?php echo htmlspecialchars($ic['name_ar']); ?></td>
                                <td class="text-secondary"><?php echo htmlspecialchars($ic['email'] ?: '-'); ?></td>
                                <td class="text-secondary"><?php echo htmlspecialchars($ic['phone'] ?: '-'); ?></td>
                                <td class="text-muted"><?php echo date('Y-m-d', strtotime($ic['created_at'])); ?></td>
                                <td class="text-end px-4">
                                    <div class="dropdown">
                                        <button class="btn btn-sm btn-light text-secondary" type="button" data-bs-toggle="dropdown">
                                            <i class="bi bi-three-dots-vertical"></i>
                                        </button>
                                        <ul class="dropdown-menu dropdown-menu-end border-0 shadow-sm">
                                            <li>
                                                <a class="dropdown-item" href="#" onclick="openStatementModal(<?php echo $ic['id']; ?>)">
                                                    <i class="bi bi-printer me-2"></i> <?php echo __('statement'); ?>
                                                </a>
                                            </li>
                                            <li>
                                                <a class="dropdown-item" href="#" onclick='openEditInsuranceModal(<?php echo json_encode($ic); ?>)'>
                                                    <i class="bi bi-pencil me-2"></i> <?php echo __('edit'); ?>
                                                </a>
                                            </li>
                                            <li><hr class="dropdown-divider"></li>
                                            <li>
                                                <a class="dropdown-item text-danger" href="#" onclick="deleteInsurance(<?php echo $ic['id']; ?>)">
                                                    <i class="bi bi-trash me-2"></i> <?php echo __('delete'); ?>
                                                </a>
                                            </li>
                                        </ul>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Pagination -->
                <div id="insurancePagination">
                <?php if ($totalPages > 1): ?>
                <div class="d-flex justify-content-between align-items-center p-3 border-top">
                    <div class="text-muted small">
                        <?php echo __('showing'); ?> <?php echo $offset + 1; ?> - <?php echo min($offset + $limit, $totalInsurance); ?> <?php echo __('of'); ?> <?php echo $totalInsurance; ?>
                    </div>
                    <nav aria-label="Page navigation">
                        <ul class="pagination pagination-sm mb-0">
                            <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                <a class="page-link" href="#" data-page="<?php echo $page - 1; ?>" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                            <?php
                            $range = 2;
                            $pages_to_show = [];
                            $pages_to_show[] = 1;
                            if ($totalPages > 1) { $pages_to_show[] = $totalPages; }
                            for ($i = $page - $range; $i <= $page + $range; $i++) {
                                if ($i > 1 && $i < $totalPages) { $pages_to_show[] = $i; }
                            }
                            $pages_to_show = array_unique($pages_to_show);
                            sort($pages_to_show);
                            
                            $prev_page = 0;
                            foreach ($pages_to_show as $p):
                                if ($prev_page > 0 && $p > $prev_page + 1): ?>
                                    <li class="page-item disabled"><span class="page-link">...</span></li>
                                <?php endif; ?>
                                <li class="page-item <?php echo $page == $p ? 'active' : ''; ?>">
                                    <a class="page-link" href="#" data-page="<?php echo $p; ?>">
                                        <?php echo $p; ?>
                                    </a>
                                </li>
                                <?php 
                                $prev_page = $p;
                            endforeach; 
                            ?>
                            <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                                <a class="page-link" href="#" data-page="<?php echo $page + 1; ?>" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        </ul>
                    </nav>
                </div>
                <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- TRANSACTIONS TAB -->
    <div class="tab-pane fade" id="transactions" role="tabpanel" aria-labelledby="transactions-tab">
        
        <!-- Search Bar -->
        <div class="card shadow-sm border-0 mb-4">
            <div class="card-body">
                <form id="transSearchForm" class="row g-3" onsubmit="return false;">
                    <div class="col-md-4">
                        <select name="trans_company_id" id="transSearchCompany" class="form-select bg-light border-0">
                            <option value=""><?php echo __('all'); ?> <?php echo __('insurance_companies'); ?></option>
                            <?php foreach ($all_insurance as $ic): ?>
                                <option value="<?php echo $ic['id']; ?>"><?php echo htmlspecialchars($ic['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <input type="date" name="trans_start_date" id="transStartDate" class="form-control bg-light border-0" placeholder="<?php echo __('start_date'); ?>">
                    </div>
                    <div class="col-md-3">
                        <input type="date" name="trans_end_date" id="transEndDate" class="form-control bg-light border-0" placeholder="<?php echo __('end_date'); ?>">
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-secondary w-100" onclick="fetchTransactions(1)"><?php echo __('search'); ?></button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card shadow-sm border-0">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light text-secondary">
                            <tr>
                                <th class="px-4 py-3">ID</th>
                                <th class="py-3"><?php echo __('payment_date'); ?></th>
                                <th class="py-3"><?php echo __('insurance_company'); ?></th>
                                <th class="py-3"><?php echo __('amount'); ?></th>
                                <th class="py-3"><?php echo __('reference_number'); ?></th>
                                <th class="py-3"><?php echo __('payment_method'); ?></th>
                                <th class="py-3"><?php echo __('notes'); ?></th>
                                <th class="py-3 text-end px-4"><?php echo __('actions'); ?></th>
                            </tr>
                        </thead>
                        <tbody id="transTableBody">
                            <?php if (empty($transactions)): ?>
                            <tr>
                                <td colspan="8" class="text-center py-5 text-muted">
                                    <i class="bi bi-cash-stack display-4 d-block mb-3"></i>
                                    <?php echo __('no_transactions_found'); ?>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($transactions as $t): ?>
                            <tr>
                                <td class="px-4 text-secondary">#<?php echo $t['id']; ?></td>
                                <td class="fw-semibold text-dark"><?php echo date('Y-m-d', strtotime($t['payment_date'])); ?></td>
                                <td class="text-secondary"><?php echo htmlspecialchars($t['company_name']); ?></td>
                                <td class="text-dark fw-bold"><?php echo format_currency($t['amount']); ?></td>
                                <td class="text-secondary"><?php echo htmlspecialchars($t['reference_number'] ?: '-'); ?></td>
                                <td class="text-secondary">
                                    <?php 
                                    $method_key = 'payment_method_' . strtolower(str_replace(' ', '_', $t['payment_method']));
                                    echo __($method_key) !== $method_key ? __($method_key) : $t['payment_method']; 
                                    ?>
                                </td>
                                <td class="text-muted small text-truncate" style="max-width: 150px;" title="<?php echo htmlspecialchars($t['notes']); ?>">
                                    <?php echo htmlspecialchars($t['notes'] ?: '-'); ?>
                                </td>
                                <td class="text-end px-4">
                                    <button class="btn btn-sm btn-light text-primary me-1" 
                                            onclick='openEditTransactionModal(<?php echo json_encode($t); ?>)'
                                            title="<?php echo __('edit'); ?>">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <button class="btn btn-sm btn-light text-danger" 
                                            onclick="deleteTransaction(<?php echo $t['id']; ?>)"
                                            title="<?php echo __('delete'); ?>">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Pagination -->
                <div id="transPagination">
                <?php if ($totalTransPages > 1): ?>
                <div class="d-flex justify-content-between align-items-center p-3 border-top">
                    <div class="text-muted small">
                        <?php echo __('showing'); ?> <?php echo $trans_offset + 1; ?> - <?php echo min($trans_offset + $trans_limit, $totalTrans); ?> <?php echo __('of'); ?> <?php echo $totalTrans; ?>
                    </div>
                    <nav aria-label="Page navigation">
                        <ul class="pagination pagination-sm mb-0">
                            <li class="page-item <?php echo $trans_page <= 1 ? 'disabled' : ''; ?>">
                                <a class="page-link" href="#" data-page="<?php echo $trans_page - 1; ?>" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                            <?php
                            $range = 2;
                            $pages_to_show = [];
                            $pages_to_show[] = 1;
                            if ($totalTransPages > 1) { $pages_to_show[] = $totalTransPages; }
                            for ($i = $trans_page - $range; $i <= $trans_page + $range; $i++) {
                                if ($i > 1 && $i < $totalTransPages) { $pages_to_show[] = $i; }
                            }
                            $pages_to_show = array_unique($pages_to_show);
                            sort($pages_to_show);
                            
                            $prev_page = 0;
                            foreach ($pages_to_show as $p):
                                if ($prev_page > 0 && $p > $prev_page + 1): ?>
                                    <li class="page-item disabled"><span class="page-link">...</span></li>
                                <?php endif; ?>
                                <li class="page-item <?php echo $trans_page == $p ? 'active' : ''; ?>">
                                    <a class="page-link" href="#" data-page="<?php echo $p; ?>">
                                        <?php echo $p; ?>
                                    </a>
                                </li>
                                <?php 
                                $prev_page = $p;
                            endforeach; 
                            ?>
                            <li class="page-item <?php echo $trans_page >= $totalTransPages ? 'disabled' : ''; ?>">
                                <a class="page-link" href="#" data-page="<?php echo $trans_page + 1; ?>" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        </ul>
                    </nav>
                </div>
                <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Insurance Modal -->
<div class="modal fade" id="addInsuranceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><?php echo __('add_insurance'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="">
                <input type="hidden" name="action" value="add_insurance">
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_en'); ?> <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name_en" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_ar'); ?> <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name_ar" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('email'); ?></label>
                        <input type="email" class="form-control" name="email">
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('phone'); ?></label>
                        <input type="text" class="form-control" name="phone">
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('discount_percentage'); ?></label>
                        <div class="input-group">
                            <input type="number" class="form-control" name="discount_percentage" step="0.01" min="0" max="100">
                            <span class="input-group-text">%</span>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('close'); ?></button>
                    <button type="submit" class="btn btn-primary"><?php echo __('save'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Insurance Modal -->
<div class="modal fade" id="editInsuranceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><?php echo __('edit'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="">
                <input type="hidden" name="action" value="edit_insurance">
                <input type="hidden" name="id" id="editInsId">
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_en'); ?> <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name_en" id="editInsNameEn" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_ar'); ?> <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name_ar" id="editInsNameAr" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('email'); ?></label>
                        <input type="email" class="form-control" name="email" id="editInsEmail">
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('phone'); ?></label>
                        <input type="text" class="form-control" name="phone" id="editInsPhone">
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('discount_percentage'); ?></label>
                        <div class="input-group">
                            <input type="number" class="form-control" name="discount_percentage" id="editInsDiscount" step="0.01" min="0" max="100">
                            <span class="input-group-text">%</span>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('close'); ?></button>
                    <button type="submit" class="btn btn-primary"><?php echo __('save_changes'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Transaction Modal -->
<div class="modal fade" id="addTransactionModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><?php echo __('add_transaction'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="">
                <input type="hidden" name="action" value="add_transaction">
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('insurance_company'); ?> <span class="text-danger">*</span></label>
                        <select name="insurance_company_id" class="form-select" required>
                            <option value=""><?php echo __('select'); ?></option>
                            <?php foreach ($all_insurance as $ic): ?>
                                <option value="<?php echo $ic['id']; ?>"><?php echo htmlspecialchars($ic['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('amount'); ?> <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><?php echo $_SESSION['currency_symbol'] ?? '$'; ?></span>
                                <input type="number" class="form-control" name="amount" step="0.001" required>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('payment_date'); ?> <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" name="payment_date" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('payment_method'); ?></label>
                            <select name="payment_method" class="form-select">
                                <option value="Check"><?php echo __('payment_method_check'); ?></option>
                                <option value="Bank Transfer"><?php echo __('payment_method_transfer'); ?></option>
                                <option value="Cash"><?php echo __('payment_method_cash'); ?></option>
                                <option value="Credit Card"><?php echo __('payment_method_card'); ?></option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('reference_number'); ?></label>
                            <input type="text" class="form-control" name="reference_number">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('notes'); ?></label>
                        <textarea class="form-control" name="notes" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('close'); ?></button>
                    <button type="submit" class="btn btn-primary"><?php echo __('save'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Transaction Modal -->
<div class="modal fade" id="editTransactionModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><?php echo __('edit_transaction'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="">
                <input type="hidden" name="action" value="edit_transaction">
                <input type="hidden" name="id" id="editTransId">
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('insurance_company'); ?> <span class="text-danger">*</span></label>
                        <select name="insurance_company_id" id="editTransCompany" class="form-select" required>
                            <option value=""><?php echo __('select'); ?></option>
                            <?php foreach ($all_insurance as $ic): ?>
                                <option value="<?php echo $ic['id']; ?>"><?php echo htmlspecialchars($ic['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('amount'); ?> <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><?php echo $_SESSION['currency_symbol'] ?? '$'; ?></span>
                                <input type="number" class="form-control" name="amount" id="editTransAmount" step="0.001" required>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('payment_date'); ?> <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" name="payment_date" id="editTransDate" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('payment_method'); ?></label>
                            <select name="payment_method" id="editTransMethod" class="form-select">
                                <option value="Check"><?php echo __('payment_method_check'); ?></option>
                                <option value="Bank Transfer"><?php echo __('payment_method_transfer'); ?></option>
                                <option value="Cash"><?php echo __('payment_method_cash'); ?></option>
                                <option value="Credit Card"><?php echo __('payment_method_card'); ?></option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('reference_number'); ?></label>
                            <input type="text" class="form-control" name="reference_number" id="editTransRef">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('notes'); ?></label>
                        <textarea class="form-control" name="notes" id="editTransNotes" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('close'); ?></button>
                    <button type="submit" class="btn btn-primary"><?php echo __('save_changes'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Statement Modal -->
<div class="modal fade" id="statementModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><?php echo __('print_statement'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="statementForm" action="print_insurance_statement.php" method="GET" target="_blank">
                <input type="hidden" name="id" id="statementInsuranceId">
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('start_date'); ?></label>
                        <input type="date" class="form-control" name="start_date" id="startDate">
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('end_date'); ?></label>
                        <input type="date" class="form-control" name="end_date" id="endDate">
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('close'); ?></button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-printer me-1"></i> <?php echo __('print'); ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Form -->
<form id="deleteForm" method="POST" style="display:none;">
    <input type="hidden" name="action" id="deleteAction">
    <input type="hidden" name="id" id="deleteId">
</form>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const searchName = document.getElementById('insSearchName');
    const searchPhone = document.getElementById('insSearchPhone');
    const insPagination = document.getElementById('insurancePagination');

    const transSearchCompany = document.getElementById('transSearchCompany');
    const transStartDate = document.getElementById('transStartDate');
    const transEndDate = document.getElementById('transEndDate');
    const transPagination = document.getElementById('transPagination');

    let timeout = null;

    // Companies Search
    if (searchName) {
        searchName.addEventListener('input', function() {
            clearTimeout(timeout);
            timeout = setTimeout(() => fetchInsurance(1), 300);
        });
    }
    if (searchPhone) {
        searchPhone.addEventListener('input', function() {
            clearTimeout(timeout);
            timeout = setTimeout(() => fetchInsurance(1), 300);
        });
    }
    if (insPagination) {
        insPagination.addEventListener('click', function(e) {
            e.preventDefault();
            const link = e.target.closest('.page-link');
            if (link && !link.parentElement.classList.contains('disabled')) {
                const page = link.getAttribute('data-page');
                if (page) fetchInsurance(page);
            }
        });
    }

    // Transactions Search
    if (transSearchCompany) {
        transSearchCompany.addEventListener('change', () => fetchTransactions(1));
    }
    if (transStartDate) {
        transStartDate.addEventListener('change', () => fetchTransactions(1));
    }
    if (transEndDate) {
        transEndDate.addEventListener('change', () => fetchTransactions(1));
    }
    if (transPagination) {
        transPagination.addEventListener('click', function(e) {
            e.preventDefault();
            const link = e.target.closest('.page-link');
            if (link && !link.parentElement.classList.contains('disabled')) {
                const page = link.getAttribute('data-page');
                if (page) fetchTransactions(page);
            }
        });
    }
    
    // Set default dates for statement
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    
    if(document.getElementById('startDate')) {
        document.getElementById('startDate').valueAsDate = firstDay;
    }
    if(document.getElementById('endDate')) {
        document.getElementById('endDate').valueAsDate = today;
    }
});

function fetchInsurance(page) {
    const name = document.getElementById('insSearchName').value;
    const phone = document.getElementById('insSearchPhone').value;
    const tableBody = document.getElementById('insuranceTableBody');
    const paginationContainer = document.getElementById('insurancePagination');

    if (tableBody) tableBody.style.opacity = '0.5';

    const params = new URLSearchParams();
    params.append('name', name);
    params.append('phone', phone);
    params.append('page', page);
    params.append('ajax_search', '1');
    // Tab defaults to companies implicitly in PHP if not specified, 
    // or we can explicit pass tab=companies

    fetch('insurance.php?' + params.toString())
        .then(response => response.json())
        .then(data => {
            if (tableBody) {
                tableBody.innerHTML = data.html;
                tableBody.style.opacity = '1';
            }
            if (paginationContainer) {
                paginationContainer.innerHTML = data.pagination;
            }
        })
        .catch(error => {
            console.error('Error fetching insurance:', error);
            if (tableBody) tableBody.style.opacity = '1';
        });
}

function fetchTransactions(page) {
    const company = document.getElementById('transSearchCompany').value;
    const start = document.getElementById('transStartDate').value;
    const end = document.getElementById('transEndDate').value;
    const tableBody = document.getElementById('transTableBody');
    const paginationContainer = document.getElementById('transPagination');

    if (tableBody) tableBody.style.opacity = '0.5';

    const params = new URLSearchParams();
    params.append('trans_company_id', company);
    params.append('trans_start_date', start);
    params.append('trans_end_date', end);
    params.append('trans_page', page);
    params.append('ajax_search', '1');
    params.append('tab', 'transactions');

    fetch('insurance.php?' + params.toString())
        .then(response => response.json())
        .then(data => {
            if (tableBody) {
                tableBody.innerHTML = data.html;
                tableBody.style.opacity = '1';
            }
            if (paginationContainer) {
                paginationContainer.innerHTML = data.pagination;
            }
        })
        .catch(error => {
            console.error('Error fetching transactions:', error);
            if (tableBody) tableBody.style.opacity = '1';
        });
}

function openStatementModal(id) {
    document.getElementById('statementInsuranceId').value = id;
    var myModal = new bootstrap.Modal(document.getElementById('statementModal'));
    myModal.show();
}

function openEditInsuranceModal(data) {
    document.getElementById('editInsId').value = data.id;
    document.getElementById('editInsNameEn').value = data.name_en;
    document.getElementById('editInsNameAr').value = data.name_ar;
    document.getElementById('editInsEmail').value = data.email || '';
    document.getElementById('editInsPhone').value = data.phone || '';
    document.getElementById('editInsDiscount').value = data.discount_percentage || 0;
    
    var myModal = new bootstrap.Modal(document.getElementById('editInsuranceModal'));
    myModal.show();
}

function deleteInsurance(id) {
    if(confirm('<?php echo __('confirm_delete'); ?>?')) {
        const form = document.getElementById('deleteForm');
        document.getElementById('deleteAction').value = 'delete_insurance';
        document.getElementById('deleteId').value = id;
        form.submit();
    }
}

function openEditTransactionModal(data) {
    document.getElementById('editTransId').value = data.id;
    document.getElementById('editTransCompany').value = data.insurance_company_id;
    document.getElementById('editTransAmount').value = data.amount;
    document.getElementById('editTransDate').value = data.payment_date;
    document.getElementById('editTransMethod').value = data.payment_method;
    document.getElementById('editTransRef').value = data.reference_number || '';
    document.getElementById('editTransNotes').value = data.notes || '';
    
    var myModal = new bootstrap.Modal(document.getElementById('editTransactionModal'));
    myModal.show();
}

function deleteTransaction(id) {
    if(confirm('<?php echo __('confirm_delete_transaction'); ?>')) {
        const form = document.getElementById('deleteForm');
        document.getElementById('deleteAction').value = 'delete_transaction';
        document.getElementById('deleteId').value = id;
        form.submit();
    }
}
</script>