<?php
$page_title = 'Daftar COA';
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="coa_data.xls"');

    $sql = "SELECT kode, akun, type_akun FROM coa";
    
    $search_term = isset($_GET['search']) ? $db->escape($_GET['search']) : '';
    $where_clauses = [];
    
    if (!empty($search_term)) {
        $where_clauses[] = " (akun LIKE '%{$search_term}%' OR kode 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>Kode</th><th>Akun</th><th>Tipe Akun</th></tr></thead>';
    echo '<tbody>';
    $i = 1;
    while ($row = $db->fetch_assoc($result)) {
        echo '<tr>';
        echo '<td>' . $i++ . '</td>';
        echo '<td>' . htmlspecialchars($row['kode']) . '</td>';
        echo '<td>' . remove_junk($row['akun']) . '</td>';
        echo '<td>' . remove_junk($row['type_akun']) . '</td>';
        echo '</tr>';
    }
    echo '</tbody>';
    echo '</table>';
    
    exit;
}

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

// Pagination and search 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 coa";
$where_clauses = [];
if (!empty($search_term)) {
    $where_clauses[] = " (akun LIKE '%{$search_term}%' OR kode LIKE '%{$search_term}%') ";
}
if (!empty($where_clauses)) {
    $sql .= " WHERE " . implode(' AND ', $where_clauses);
}

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

// Build the main SQL query for displaying data
$sql = "SELECT kode, akun, type_akun FROM coa";

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

$sql .= " LIMIT {$per_page} OFFSET {$start}";
$coa_data = 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">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
</div>

<div class="row" style="display: flex; justify-content: space-between; flex-wrap: wrap;">
    <div class="col-md-12">
        <div class="panel panel-info">
            <div class="panel-heading">
                <i class="glyphicon glyphicon-th"></i> Total Akun
            </div>
            <div class="panel-body text-center" style="font-size: 12px;">
                <h2><?php echo number_format($total_coa_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 COA</span>
                </strong>
                <a href="add_coa.php" class="btn btn-info pull-right">Tambah Akun COA</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 Kode atau Akun..." value="<?php echo htmlspecialchars($search_term); ?>">
                        </div>
                        <div class="col-md-2">
                            <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-4">
                            <button type="submit" class="btn btn-primary">Filter</button>
                            <a href="coa.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: 25%;">Kode</th>
                                <th style="width: 40%;">Akun</th>
                                <th class="text-center" style="width: 25%;">Tipe Akun</th>
                                <th class="text-center" style="width: 100px;">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($coa_data)): ?>
                                <?php $i = $start + 1; ?>
                                <?php foreach ($coa_data as $coa) : ?>
                                    <tr>
                                        <td class="text-center"><?php echo (int)$i++; ?></td>
                                        <td><?php echo htmlspecialchars($coa['kode']); ?></td>
                                        <td><?php echo remove_junk($coa['akun']); ?></td>
                                        <td class="text-center"><?php echo remove_junk($coa['type_akun']); ?></td>
                                        <td class="text-center">
                                            <div class="btn-group">
                                                <button type="button" class="btn btn-xs btn-info" data-toggle="modal" data-target="#coaDetailModal"
                                                        data-kode="<?php echo htmlspecialchars($coa['kode']); ?>"
                                                        data-akun="<?php echo htmlspecialchars($coa['akun']); ?>"
                                                        data-type-akun="<?php echo htmlspecialchars($coa['type_akun']); ?>"
                                                        title="Lihat Detail">
                                                    <i class="glyphicon glyphicon-eye-open"></i>
                                                </button>
                                                <a href="edit_coa.php?id=<?php echo urlencode($coa['kode']);?>" class="btn btn-xs btn-warning" title="Edit" data-toggle="tooltip">
                                                    <i class="glyphicon glyphicon-pencil"></i>
                                                </a>
                                                <a href="delete_coa.php?id=<?php echo urlencode($coa['kode']);?>" class="btn btn-xs btn-danger" title="Hapus" data-toggle="tooltip" onclick="return confirm('Apakah Anda yakin ingin menghapus akun ini?');">
                                                    <i class="glyphicon glyphicon-remove"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="5" class="text-center">Tidak ada akun COA 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>

<div class="modal fade" id="coaDetailModal" tabindex="-1" role="dialog" aria-labelledby="coaDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="coaDetailModalLabel">Detail Akun COA</h4>
            </div>
            <div class="modal-body">
                <p><strong>Kode:</strong> <span id="modal-coa-kode"></span></p>
                <p><strong>Akun:</strong> <span id="modal-coa-akun"></span></p>
                <p><strong>Tipe Akun:</strong> <span id="modal-coa-type-akun"></span></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>

<script>
    $('#coaDetailModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget);
        var kode = button.data('kode');
        var akun = button.data('akun');
        var typeAkun = button.data('type-akun');

        var modal = $(this);
        modal.find('#modal-coa-kode').text(kode);
        modal.find('#modal-coa-akun').text(akun);
        modal.find('#modal-coa-type-akun').text(typeAkun);
    });
</script>

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