<?php
$page_title = 'Customer List';
require_once('includes/load.php');
page_require_level(5);

// Check if a form was submitted for search or pagination
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['export_excel'])) {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="customer_data.xls"');

    $sql = "SELECT c.*, a.akun AS coa_name
            FROM customers c
            LEFT JOIN coa a ON c.coa_kode = a.kode";

    $search_term = isset($_GET['search']) ? $db->escape($_GET['search']) : '';

    $where_clauses = [];
    if (!empty($search_term)) {
        $where_clauses[] = " (c.name LIKE '%{$search_term}%' OR c.contact_person LIKE '%{$search_term}%' OR c.phone LIKE '%{$search_term}%') ";
    }

    if (!empty($where_clauses)) {
        $sql .= " WHERE " . implode(' AND ', $where_clauses);
    }
    
    $result = $db->query($sql);

    // Generate table for export
    echo '<table border="1">';
    echo '<thead><tr><th>#</th><th>Nama</th><th>Alamat</th><th>No. Telepon</th><th>Email</th><th>Contact Person</th><th>Kode COA</th><th>Nama Akun COA</th></tr></thead>';
    echo '<tbody>';
    $i = 1;
    while ($row = $db->fetch_assoc($result)) {
        echo '<tr>';
        echo '<td>' . $i++ . '</td>';
        echo '<td>' . remove_junk($row['name']) . '</td>';
        echo '<td>' . remove_junk($row['address']) . '</td>';
        echo '<td>' . htmlspecialchars($row['phone']) . '</td>';
        echo '<td>' . htmlspecialchars($row['email']) . '</td>';
        echo '<td>' . htmlspecialchars($row['contact_person']) . '</td>';
        echo '<td>' . htmlspecialchars($row['coa_kode']) . '</td>';
        echo '<td>' . htmlspecialchars($row['coa_name']) . '</td>';
        echo '</tr>';
    }
    echo '</tbody>';
    echo '</table>';

    exit;
}

// Dashboard Metrics
$total_customers_count = find_by_sql("SELECT COUNT(*) AS total FROM customers")[0]['total'];

// Pagination, search, and filter settings
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10;
$search_term = isset($_GET['search']) ? $db->escape($_GET['search']) : '';

// Build the SQL query for counting total rows
$sql = "SELECT COUNT(*) AS total FROM customers c";
$where_clauses = [];
if (!empty($search_term)) {
    $where_clauses[] = " (c.name LIKE '%{$search_term}%' OR c.contact_person LIKE '%{$search_term}%' OR c.phone LIKE '%{$search_term}%') ";
}
if (!empty($where_clauses)) {
    $sql .= " WHERE " . implode(' AND ', $where_clauses);
}

$result = $db->query($sql);
$total_customers_filtered = $db->fetch_assoc($result)['total'];
$total_pages = ceil($total_customers_filtered / $per_page);
$start = ($page - 1) * $per_page;

// Build the main SQL query for displaying data
$sql = "SELECT c.*, a.akun AS coa_name
        FROM customers c
        LEFT JOIN coa a ON c.coa_kode = a.kode";

if (!empty($where_clauses)) {
    $sql .= " WHERE " . implode(' AND ', $where_clauses);
}

$sql .= " LIMIT {$per_page} OFFSET {$start}";
$customers = find_by_sql($sql);
?>

<?php include_once('layouts/header.php'); ?>

<style>
    .table thead th,
    .table tbody td {
        font-size: 12px;
    }
    .panel-body h2 {
        font-size: 20px;
    }
    .panel-heading i {
        font-size: 12px;
    }
</style>

<div class="row" style="display: flex; justify-content: space-between; flex-wrap: wrap;">
    <div class="col-md-3" style="flex: 1 1 23%;">
        <div class="panel panel-info">
            <div class="panel-heading">
                <i class="glyphicon glyphicon-user"></i> Total Pelanggan
            </div>
            <div class="panel-body text-center" style="font-size: 12px;">
                <h2><?php echo number_format($total_customers_count); ?></h2>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <strong>
                    <span class="glyphicon glyphicon-th"></span>
                    <span>Daftar Pelanggan</span>
                </strong>
                <a href="add_customer" class="btn btn-info pull-right">Tambah Pelanggan</a>
            </div>
            <div class="panel-body">
                <form action="" method="GET" class="form-horizontal mb-4">
                    <div class="form-group clearfix">
                        <div class="col-md-6">
                            <input type="text" name="search" class="form-control" placeholder="Cari nama, kontak, atau telepon..." value="<?php echo htmlspecialchars($search_term); ?>">
                        </div>
                        <div class="col-md-3">
                            <select name="per_page" class="form-control">
                                <option value="10" <?php if ($per_page == 10) echo 'selected'; ?>>10 per halaman</option>
                                <option value="25" <?php if ($per_page == 25) echo 'selected'; ?>>25 per halaman</option>
                                <option value="50" <?php if ($per_page == 50) echo 'selected'; ?>>50 per halaman</option>
                                <option value="100" <?php if ($per_page == 100) echo 'selected'; ?>>100 per halaman</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <button type="submit" class="btn btn-primary">Filter</button>
                            <a href="customers.php" class="btn btn-default">Reset</a>
                            <a href="?export_excel=1&search=<?php echo urlencode($search_term); ?>" class="btn btn-success pull-right">Export Excel</a>
                        </div>
                    </div>
                </form>

                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th class="text-center" style="width: 50px;">#</th>
                                <th style="width: 15%;">Nama Pelanggan</th>
                                <th style="width: 25%;">Alamat</th>
                                <th class="text-center" style="width: 15%;">No. Telepon</th>
                                <th class="text-center" style="width: 15%;">Email</th>
                                <th class="text-center" style="width: 15%;">Contact Person</th>
                                <th class="text-center" style="width: 10%;">Kode COA</th>
                                <th class="text-center" style="width: 100px;">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($customers)): ?>
                                <?php $i = $start + 1; ?>
                                <?php foreach ($customers as $customer) : ?>
                                    <tr>
                                        <td class="text-center"><?php echo (int)$i++; ?></td>
                                        <td><?php echo remove_junk($customer['name']); ?></td>
                                        <td><?php echo remove_junk($customer['address']); ?></td>
                                        <td><?php echo htmlspecialchars($customer['phone']); ?></td>
                                        <td><?php echo htmlspecialchars($customer['email']); ?></td>
                                        <td><?php echo htmlspecialchars($customer['contact_person']); ?></td>
                                        <td><?php echo htmlspecialchars($customer['coa_kode']); ?></td>
                                        <td class="text-center">
                                            <div class="btn-group">
                                                <a href="edit_customer.php?id=<?php echo (int)$customer['id'];?>" class="btn btn-xs btn-warning" title="Edit" data-toggle="tooltip">
                                                    <i class="glyphicon glyphicon-pencil"></i>
                                                </a>
                                                <a href="delete_customer.php?id=<?php echo (int)$customer['id'];?>" class="btn btn-xs btn-danger" title="Hapus" data-toggle="tooltip" onclick="return confirm('Apakah Anda yakin ingin menghapus pelanggan ini?');">
                                                    <i class="glyphicon glyphicon-remove"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="8" class="text-center">Tidak ada pelanggan ditemukan.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($total_pages > 1): ?>
                    <nav aria-label="Page navigation">
                        <ul class="pagination pull-right">
                            <li class="page-item <?php if ($page <= 1) echo 'disabled'; ?>">
                                <a class="page-link" href="?page=<?php echo $page - 1; ?>&per_page=<?php echo $per_page; ?>&search=<?php echo urlencode($search_term); ?>">Prev</a>
                            </li>
                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <li class="page-item <?php if ($i == $page) echo 'active'; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&per_page=<?php echo $per_page; ?>&search=<?php echo urlencode($search_term); ?>"><?php echo $i; ?></a>
                                </li>
                            <?php endfor; ?>
                            <li class="page-item <?php if ($page >= $total_pages) echo 'disabled'; ?>">
                                <a class="page-link" href="?page=<?php echo $page + 1; ?>&per_page=<?php echo $per_page; ?>&search=<?php echo urlencode($search_term); ?>">Next</a>
                            </li>
                        </ul>
                    </nav>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php include_once('layouts/footer.php'); ?>