<?php
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include_once '../db/koneksi.php';

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['kode_admin'])) {
    echo '
    <script>
        alert("Terjadi kesalahan, harap masuk kembali!");
        window.location.replace("' . $alamat_admin . 'keluar.php");
    </script>
    ';
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update') {
    $id              = mysqli_real_escape_string($koneksi, $_POST['id']);
    $provider_name   = mysqli_real_escape_string($koneksi, $_POST['provider_name']);
    $provider_type   = mysqli_real_escape_string($koneksi, $_POST['provider_type']);
    $slug            = mysqli_real_escape_string($koneksi, $_POST['slug']);
    $status          = mysqli_real_escape_string($koneksi, $_POST['status']);
    $provider_image  = mysqli_real_escape_string($koneksi, $_POST['provider_image']);
    $code            = mysqli_real_escape_string($koneksi, $_POST['code']);

    $queryUpdate = "
        UPDATE tb_provider
        SET 
            provider_name  = '$provider_name',
            provider_type  = '$provider_type',
            slug           = '$slug',
            status         = $status,
            provider_image = '$provider_image',
            code           = '$code'
        WHERE id = '$id'
    ";

    if (mysqli_query($koneksi, $queryUpdate)) {
        $_SESSION['success'] = "Data provider berhasil diperbarui.";
        echo '<script>window.location.replace("'.$alamat_admin.'provider")</script>';
    } else {
        $_SESSION['error'] = "Gagal memperbarui data provider: " . mysqli_error($koneksi);
    }
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create') {
    $provider_name   = mysqli_real_escape_string($koneksi, $_POST['provider_name']);
    $provider_type   = mysqli_real_escape_string($koneksi, $_POST['provider_type']);
    $slug            = mysqli_real_escape_string($koneksi, $_POST['slug']);
    $status          = (int)$_POST['status'];
    $provider_image  = mysqli_real_escape_string($koneksi, $_POST['provider_image']);
    $code            = mysqli_real_escape_string($koneksi, $_POST['code']);

    $cek = mysqli_query($koneksi, "SELECT id FROM tb_provider WHERE slug='$slug' LIMIT 1");
    if (mysqli_num_rows($cek) > 0) {
        $_SESSION['error'] = "Slug atau Code sudah digunakan.";
        echo '<script>window.location.replace("'.$alamat_admin.'provider")</script>';
        exit();
    }

    $queryInsert = "
        INSERT INTO tb_provider (provider_name, provider_type, slug, status, provider_image, code)
        VALUES ('$provider_name', '$provider_type', '$slug', $status, '$provider_image', '$code')
    ";

    if (mysqli_query($koneksi, $queryInsert)) {
        $_SESSION['success'] = "Provider berhasil ditambahkan.";
        echo '<script>window.location.replace("'.$alamat_admin.'provider")</script>';
    } else {
        $_SESSION['error'] = "Gagal menambahkan provider: " . mysqli_error($koneksi);
        echo '<script>window.location.replace("'.$alamat_admin.'provider")</script>';
    }
    exit();
}


// === PAGINATION & SEARCH ===
$limit = 50;
$page = isset($_POST['page']) ? (int)$_POST['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

$search = isset($_POST['search']) ? mysqli_real_escape_string($koneksi, $_POST['search']) : '';

$where = "";
if (!empty($search)) {
    $search_safe = str_replace(['%', '_'], ['\%', '\_'], $search);
    $where = "WHERE LOWER(provider_name) LIKE LOWER('%$search_safe%') 
              OR LOWER(code) LIKE LOWER('%$search_safe%')
              OR LOWER(slug) LIKE LOWER('%$search_safe%')";
}

$totalQuery = mysqli_query($koneksi, "SELECT COUNT(*) as total FROM tb_provider $where");
$totalData = mysqli_fetch_assoc($totalQuery)['total'];
$totalPages = ceil($totalData / $limit);

$query = "SELECT * FROM tb_provider $where ORDER BY id ASC LIMIT $limit OFFSET $offset";
$providerlist = mysqli_query($koneksi, $query);
?>

<div class="container-xxl flex-grow-1 container-p-y">

    <div class="row gy-4 mb-4">
        <div class="col-md-6">
            <h4 class="fw-bold mb-0 text-center text-md-start">Provider List</h4>
        </div>
        <div class="col-md-6 text-center text-md-end">
            <span><?php echo ucapan() . ', ' . tanggalIndonesia(date('Y-m-d'), true) . ', '; ?></span>
            <span id="jam_sekarang">Jam </span>
        </div>
    </div>

    <?php if (isset($_SESSION['success'])): ?>
        <div class="alert alert-success"><?= $_SESSION['success']; unset($_SESSION['success']); ?></div>
    <?php elseif (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger"><?= $_SESSION['error']; unset($_SESSION['error']); ?></div>
    <?php endif; ?>

    <div class="card table-responsive p-3">
        <button class="btn btn-success me-2" style="width: 180px; text-align: center;text-size: 0.8rem;" data-bs-toggle="modal" data-bs-target="#modalTambahProvider">
         <i class="mdi mdi-plus me-1"></i> Tambah Provider
        </button>
        <form method="post" id="filterForm" class="mb-3 d-flex flex-wrap gap-2 justify-content-end">
            <input type="hidden" name="page" id="pageInput" value="<?= $page; ?>">
            <input type="text" name="search" class="form-control w-auto" placeholder="Cari provider..." 
                value="<?= htmlspecialchars($search); ?>">
            <button type="submit" class="btn btn-primary">Search</button>
        </form>

        <table class="table table-hover align-middle">
            <thead class="table-light">
                <tr>
                    <th class="text-center">No.</th>
                    <th class="text-center">Code</th>
                    <th class="text-center">Provider Name</th>
                    <th class="text-center">Slug</th>
                    <th class="text-center">Type</th>
                    <th class="text-center">Status</th>
                    <th class="text-center">Image</th>
                    <th class="text-center">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php
                if (mysqli_num_rows($providerlist) > 0) {
                    $no = $offset + 1;
                    while ($data = mysqli_fetch_assoc($providerlist)) {
                        $id = $data['id'];
                        $status_class = ($data['status'] === 1 || $data['status'] === 0) ? 'text-success' : 'text-danger';

                        $local_image = "../uploads/provider/slots/" . htmlspecialchars($data['slug']) . ".avif";
                        $local_image2 = "../uploads/provider/slots/" . htmlspecialchars($data['slug']) . ".webp";
                        $provider_image = htmlspecialchars($data['provider_image']);

                        if (file_exists($local_image)) {
                            $img_src = $local_image;
                        } else if (file_exists($local_image2)) {
                            $img_src = $local_image2;
                        } else {
                            $img_src = $provider_image;
                        }
                    ?>
                        <tr>
                            <td class="text-center"><?= $no++; ?></td>
                            <td class="text-center"><?= htmlspecialchars($data['code']); ?></td>
                            <td class="text-center"><?= htmlspecialchars($data['provider_name']); ?></td>
                            <td class="text-center"><?= htmlspecialchars($data['slug']); ?></td>
                            <td class="text-center"><?= htmlspecialchars($data['provider_type']); ?></td>
                            <td class="text-center">
                                <span class="badge <?= ((int)$data['status'] === 1) ? 'bg-success' : 'bg-danger'; ?>">
                                    <?= (int)$data['status'] === 1 ? 'Aktif':'Nonaktif'; ?>
                                </span>
                            </td>
                            <td class="text-center">
                                <img src="<?= htmlspecialchars($img_src); ?>" 
                                     alt="Provider Image" class="img-fluid rounded" style="width: 80px;">
                            </td>
                            <td class="text-center">
                                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#modalUbahProvider<?= $id; ?>">
                                    <i class="mdi mdi-cog me-1"></i> Ubah
                                </button>
                            </td>
                        </tr>

                        <!-- Modal Ubah Provider -->
                        <div class="modal fade" id="modalUbahProvider<?= $id; ?>" tabindex="-1" aria-labelledby="modalUbahProviderLabel<?= $id; ?>" aria-hidden="true">
                            <div class="modal-dialog modal-lg modal-dialog-centered">
                                <div class="modal-content">
                                    <form method="post">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="modalUbahProviderLabel<?= $id; ?>">Ubah Provider: <?= htmlspecialchars($data['provider_name']); ?></h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body">
                                            <input type="hidden" name="action" value="update">
                                            <input type="hidden" name="id" value="<?= $id; ?>">

                                            <div class="mb-3">
                                                <label class="form-label">Code</label>
                                                <input type="text" class="form-control" name="code" value="<?= htmlspecialchars($data['code']); ?>">
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label">Provider Name</label>
                                                <input type="text" class="form-control" name="provider_name" value="<?= htmlspecialchars($data['provider_name']); ?>" required>
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label">Slug</label>
                                                <input type="text" class="form-control" name="slug" value="<?= htmlspecialchars($data['slug']); ?>" required>
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label">Type</label>
                                                <input type="text" class="form-control" name="provider_type" value="<?= htmlspecialchars($data['provider_type']); ?>" required>
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label">Status</label>
                                                <select name="status" class="form-select">
                                                    <option value="1" <?= ((int)$data['status'] === 1) ? 'selected' : ''; ?>>Aktif</option>
                                                    <option value="0" <?= ((int)$data['status'] === 0) ? 'selected' : ''; ?>>Non-Aktif</option>
                                                </select>
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label">Provider Image URL</label>
                                                <input type="url" class="form-control" name="provider_image" value="<?= htmlspecialchars($data['provider_image']); ?>">
                                            </div>
                                        </div>

                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                                            <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                <?php
                    }
                } else {
                    echo '<tr><td colspan="8" class="text-center text-muted">Tidak ada data provider ditemukan.</td></tr>';
                }
                ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPages > 1): ?>
    <nav aria-label="Page navigation" class="mt-4">
        <ul class="pagination justify-content-center">
            <li class="page-item <?= ($page <= 1) ? 'disabled' : ''; ?>">
                <button type="button" class="page-link" onclick="changePage(<?= $page - 1; ?>)">Previous</button>
            </li>

            <?php
            $showPages = 2;
            if ($page > ($showPages + 2)) {
                echo '<li class="page-item"><button type="button" class="page-link" onclick="changePage(1)">1</button></li>';
                echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
            }

            for ($i = max(1, $page - $showPages); $i <= min($totalPages, $page + $showPages); $i++) {
                $activeClass = ($i == $page) ? 'active' : '';
                echo '<li class="page-item ' . $activeClass . '">
                        <button type="button" class="page-link" onclick="changePage(' . $i . ')">' . $i . '</button>
                      </li>';
            }

            if ($page < $totalPages - ($showPages + 1)) {
                echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                echo '<li class="page-item"><button type="button" class="page-link" onclick="changePage(' . $totalPages . ')">' . $totalPages . '</button></li>';
            }
            ?>

            <li class="page-item <?= ($page >= $totalPages) ? 'disabled' : ''; ?>">
                <button type="button" class="page-link" onclick="changePage(<?= $page + 1; ?>)">Next</button>
            </li>
        </ul>
    </nav>
    <?php endif; ?>
</div>

<!-- Modal Tambah Provider -->
<div class="modal fade" id="modalTambahProvider" tabindex="-1" aria-labelledby="modalTambahProviderLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <form method="post">
        <div class="modal-header">
          <h5 class="modal-title" id="modalTambahProviderLabel">Tambah Provider</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>

        <div class="modal-body">
          <input type="hidden" name="action" value="create">

          <div class="mb-3">
            <label class="form-label">Provider code</label>
            <input type="text" class="form-control" name="code" required>
          </div>

          <div class="mb-3">
            <label class="form-label">Provider name</label>
            <input type="text" class="form-control" name="provider_name" required>
          </div>

          <div class="mb-3">
            <label class="form-label">Slug</label>
            <input type="text" class="form-control" name="slug" required>
          </div>

          <div class="mb-3">
            <label class="form-label">Type (SL/LC/SB/PK/LK/OT)</label>
            <input type="text" class="form-control" name="provider_type" required>
          </div>

          <div class="mb-3">
            <label class="form-label">Status</label>
            <select name="status" class="form-select">
              <option value="1" selected>Aktif</option>
              <option value="0">Non-Aktif</option>
            </select>
          </div>

          <div class="mb-3">
            <label class="form-label">Provider Image URL</label>
            <input type="url" class="form-control" name="provider_image">
          </div>
        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
          <button type="submit" class="btn btn-success">Tambah</button>
        </div>
      </form>
    </div>
  </div>
</div>


<script>
function changePage(page) {
    document.getElementById('pageInput').value = page;
    document.getElementById('filterForm').submit();
}
</script>
