<?php
// admin/berita/index.php
$pageTitle = 'Manajemen Berita';
require_once '../../includes/config.php';
require_once '../../includes/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/auth.php';

// Mulai session jika belum dimulai
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Cek apakah user sudah login dan role-nya admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'admin') {
    // Redirect ke halaman login jika belum login atau bukan admin
    setFlash('login_required', 'Anda harus login sebagai admin untuk mengakses halaman ini', 'danger');
    header('Location: ' . SITE_URL . '/auth/login.php');
    exit;
}

// Koneksi database
$db = dbConnect();

// Handle aksi delete jika ada
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $id = $_GET['id'];
    
    // Ambil informasi gambar berita sebelum dihapus
    $db->query("SELECT gambar FROM berita WHERE id = :id");
    $db->bind(':id', $id);
    $berita = $db->single();
    
    // Hapus berita dari database
    $db->query("DELETE FROM berita WHERE id = :id");
    $db->bind(':id', $id);
    
    if ($db->execute()) {
        // Hapus file gambar jika ada
        if ($berita && $berita->gambar && $berita->gambar != 'default.jpg') {
            $gambar_path = UPLOAD_DIR . 'berita/' . $berita->gambar;
            if (file_exists($gambar_path)) {
                unlink($gambar_path);
            }
        }
        
        // Log aktivitas
        logActivity('Menghapus berita', 'berita', $id, "Admin menghapus berita dengan ID: $id");
        
        setFlash('berita', 'Berita berhasil dihapus', 'success');
    } else {
        setFlash('berita', 'Berita gagal dihapus', 'danger');
    }
    
    // Redirect ke halaman berita
    header('Location: ' . SITE_URL . '/admin/berita/index.php');
    exit;
}

// Pagination
$current_page = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = 10;
$offset = ($current_page - 1) * $limit;

// Filter
$search = isset($_GET['search']) ? $_GET['search'] : '';

// Query untuk menghitung total berita
$query_count = "SELECT COUNT(*) as total FROM berita WHERE 1=1";
$query_params = [];

if (!empty($search)) {
    $query_count .= " AND (judul LIKE :search OR konten LIKE :search)";
    $query_params[':search'] = "%$search%";
}

$db->query($query_count);
foreach ($query_params as $param => $value) {
    $db->bind($param, $value);
}
$total_rows = $db->single()->total;
$total_pages = ceil($total_rows / $limit);

// Query untuk mengambil data berita
$query = "SELECT b.*, u.nama_lengkap as created_by_name
          FROM berita b
          LEFT JOIN users u ON b.created_by = u.id
          WHERE 1=1";

if (!empty($search)) {
    $query .= " AND (b.judul LIKE :search OR b.konten LIKE :search)";
}

$query .= " ORDER BY b.created_at DESC LIMIT :offset, :limit";

$db->query($query);
foreach ($query_params as $param => $value) {
    $db->bind($param, $value);
}
$db->bind(':offset', $offset, PDO::PARAM_INT);
$db->bind(':limit', $limit, PDO::PARAM_INT);
$berita_list = $db->resultSet();

// Include header admin
require_once '../../includes/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar Admin -->
        <?php require_once '../../includes/sidebar-admin.php'; ?>
        
        <!-- Content Area -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">Manajemen Berita</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="<?= SITE_URL ?>/admin/berita/tambah.php" class="btn btn-sm btn-success">
                        <i class="fas fa-plus me-1"></i> Tambah Berita
                    </a>
                </div>
            </div>

            <?php flash(); ?>

            <!-- Filter & Search -->
            <div class="card mb-4">
                <div class="card-body">
                    <form action="" method="get" class="row g-3">
                        <div class="col-md-6">
                            <label for="search" class="form-label">Cari</label>
                            <input type="text" class="form-control" id="search" name="search" placeholder="Cari judul atau konten berita..." value="<?= $search ?>">
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2">
                                <i class="fas fa-search me-1"></i> Cari
                            </button>
                            <a href="<?= SITE_URL ?>/admin/berita/index.php" class="btn btn-secondary">
                                <i class="fas fa-sync-alt me-1"></i> Reset
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Tabel Berita -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead>
                                <tr>
                                    <th scope="col" width="5%">#</th>
                                    <th scope="col" width="15%">Gambar</th>
                                    <th scope="col" width="30%">Judul</th>
                                    <th scope="col" width="25%">Konten</th>
                                    <th scope="col" width="15%">Tanggal</th>
                                    <th scope="col" width="10%">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($berita_list)): ?>
                                    <tr>
                                        <td colspan="6" class="text-center py-4">Tidak ada data berita</td>
                                    </tr>
                                <?php else: ?>
                                    <?php $no = $offset + 1; ?>
                                    <?php foreach ($berita_list as $berita): ?>
                                        <tr>
                                            <th scope="row"><?= $no++ ?></th>
                                            <td>
                                                <img src="<?= SITE_URL ?>/assets/uploads/berita/<?= $berita->gambar ?? 'default.jpg' ?>" class="img-thumbnail" alt="<?= $berita->judul ?>" style="width: 100px; height: 60px; object-fit: cover;">
                                            </td>
                                            <td>
                                                <strong><?= $berita->judul ?></strong>
                                                <div class="small text-muted">
                                                    Dibuat oleh: <?= $berita->created_by_name ?>
                                                </div>
                                            </td>
                                            <td>
                                                <?= potongTeks(strip_tags($berita->konten), 100) ?>
                                            </td>
                                            <td><?= date('d/m/Y H:i', strtotime($berita->created_at)) ?></td>
                                            <td>
                                                <a href="<?= SITE_URL ?>/admin/berita/edit.php?id=<?= $berita->id ?>" class="btn btn-sm btn-primary mb-1 w-100">
                                                    <i class="fas fa-edit"></i> Edit
                                                </a>
                                                <a href="<?= SITE_URL ?>/admin/berita/index.php?action=delete&id=<?= $berita->id ?>" class="btn btn-sm btn-danger w-100" onclick="return confirm('Yakin ingin menghapus berita ini?')">
                                                    <i class="fas fa-trash"></i> Hapus
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center">
                                <li class="page-item <?= ($current_page <= 1) ? 'disabled' : '' ?>">
                                    <a class="page-link" href="<?= SITE_URL ?>/admin/berita/index.php?page=<?= $current_page - 1 ?><?= !empty($search) ? '&search=' . $search : '' ?>">Previous</a>
                                </li>
                                
                                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                    <li class="page-item <?= ($current_page == $i) ? 'active' : '' ?>">
                                        <a class="page-link" href="<?= SITE_URL ?>/admin/berita/index.php?page=<?= $i ?><?= !empty($search) ? '&search=' . $search : '' ?>"><?= $i ?></a>
                                    </li>
                                <?php endfor; ?>
                                
                                <li class="page-item <?= ($current_page >= $total_pages) ? 'disabled' : '' ?>">
                                    <a class="page-link" href="<?= SITE_URL ?>/admin/berita/index.php?page=<?= $current_page + 1 ?><?= !empty($search) ? '&search=' . $search : '' ?>">Next</a>
                                </li>
                            </ul>
                        </nav>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

<?php require_once '../../includes/footer.php'; ?>