<?php
require_once '../includes/auth.php';
require_once '../config/database.php';
require_once '../config/logger.php';

requireLogin();
requireRole(['admin','diocesan_chairman','diocese_chairman','diocesan_secretary','diocesan_treasurer','diocesan_dom','diocesan_music_director']);

$basePath = '..';

// Determine scope
$userId = $_SESSION['user_id'];
$me = fetchRow("SELECT u.id, u.full_name, u.diocese_id, r.role_key FROM users u JOIN roles r ON u.role_id=r.id WHERE u.id=?", [$userId]);
$isAdmin = hasRole(['admin']);
$myDioceseId = $me['diocese_id'] ?? null;

// Filters
$statusFilter = isset($_GET['status']) ? trim($_GET['status']) : 'pending';
if (!in_array($statusFilter, ['all','pending','approved','rejected'], true)) { $statusFilter = 'pending'; }
$fromDate = isset($_GET['from']) ? trim($_GET['from']) : '';
$toDate = isset($_GET['to']) ? trim($_GET['to']) : '';
$filterDioceseId = $isAdmin ? (isset($_GET['diocese_id']) ? (int)$_GET['diocese_id'] : 0) : 0;
$dioceses = $isAdmin ? fetchRows("SELECT id, name FROM dioceses ORDER BY name") : [];

// Load ads per filters (defaults to pending approvals)
$sql = "SELECT a.*, u.full_name AS creator_name, r.role_key AS creator_role, d.name AS creator_diocese
        FROM ads a
        JOIN users u ON a.created_by = u.id
        JOIN roles r ON u.role_id = r.id
        LEFT JOIN dioceses d ON u.diocese_id = d.id
        WHERE 1=1";
$params = [];

if ($statusFilter !== 'all') {
    if ($statusFilter === 'pending') {
        $sql .= " AND a.status='pending' AND a.workflow_state='pending_approval'";
    } elseif ($statusFilter === 'approved') {
        $sql .= " AND a.status='approved'";
    } elseif ($statusFilter === 'rejected') {
        $sql .= " AND a.status='rejected'";
    }
}

if (!$isAdmin && !empty($myDioceseId)) {
    $sql .= " AND u.diocese_id = ?";
    $params[] = (int)$myDioceseId;
}

if ($isAdmin && $filterDioceseId > 0) {
    $sql .= " AND u.diocese_id = ?";
    $params[] = (int)$filterDioceseId;
}

if ($fromDate !== '' && strtotime($fromDate) !== false) {
    $sql .= " AND a.created_at >= ?";
    $params[] = date('Y-m-d 00:00:00', strtotime($fromDate));
}
if ($toDate !== '' && strtotime($toDate) !== false) {
    $sql .= " AND a.created_at <= ?";
    $params[] = date('Y-m-d 23:59:59', strtotime($toDate));
}

$sql .= " ORDER BY a.created_at DESC";
$pendingAds = fetchRows($sql, $params);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Adverts - GHAMECC</title>
    <?php include '../includes/favicon.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<?php include '../includes/navbar.php'; ?>
<div class="container-fluid">
    <div class="row">
        <?php include '../includes/sidebar.php'; ?>
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h1 class="h2">Manage Adverts</h1>
                <a href="submit.php" class="btn btn-primary"><i class="fas fa-plus me-2"></i>Submit New Advert</a>
            </div>

            <form method="get" class="row g-2 mb-3">
                <div class="col-md-3">
                    <select name="status" class="form-select">
                        <option value="pending" <?php echo $statusFilter==='pending'?'selected':''; ?>>Pending</option>
                        <option value="approved" <?php echo $statusFilter==='approved'?'selected':''; ?>>Approved</option>
                        <option value="rejected" <?php echo $statusFilter==='rejected'?'selected':''; ?>>Rejected</option>
                        <option value="all" <?php echo $statusFilter==='all'?'selected':''; ?>>All</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <input type="date" name="from" class="form-control" value="<?php echo htmlspecialchars($fromDate); ?>">
                </div>
                <div class="col-md-3">
                    <input type="date" name="to" class="form-control" value="<?php echo htmlspecialchars($toDate); ?>">
                </div>
                <?php if ($isAdmin): ?>
                <div class="col-md-3">
                    <select name="diocese_id" class="form-select">
                        <option value="0">All Dioceses</option>
                        <?php foreach ($dioceses as $d): ?>
                            <option value="<?php echo (int)$d['id']; ?>" <?php echo $filterDioceseId===(int)$d['id']?'selected':''; ?>><?php echo htmlspecialchars($d['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="col-12">
                    <button class="btn btn-outline-primary btn-sm" type="submit">Filter</button>
                    <a class="btn btn-outline-secondary btn-sm" href="manage.php">Reset</a>
                </div>
            </form>

            <?php if (isset($_GET['paid'])): ?>
                <div class="alert alert-success">Payment verified. The advert is now awaiting approval.</div>
            <?php endif; ?>

            <div class="card mb-4">
                <div class="card-header">
                    Adverts
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-striped mb-0">
                            <thead>
                                <tr>
                                    <th>Title</th>
                                    <th>Creator</th>
                                    <th>Level</th>
                                    <th>Diocese</th>
                                    <th>Price</th>
                                    <th>Payment</th>
                                    <th>Active</th>
                                    <th>Submitted</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($pendingAds)): ?>
                                    <tr><td colspan="8" class="text-center text-muted py-4">No adverts awaiting approval.</td></tr>
                                <?php else: foreach ($pendingAds as $ad): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($ad['title']); ?></td>
                                        <td><?php echo htmlspecialchars($ad['creator_name']); ?></td>
                                        <td><?php echo htmlspecialchars($ad['creator_role']); ?></td>
                                        <td><?php echo htmlspecialchars($ad['creator_diocese'] ?? ''); ?></td>
                                        <td>GHS <?php echo number_format((float)$ad['price'], 2); ?></td>
                                        <td><span class="badge bg-<?php echo $ad['payment_status']==='paid'?'success':($ad['payment_status']==='waived'?'secondary':'warning'); ?>"><?php echo htmlspecialchars($ad['payment_status']); ?></span></td>
                                        <td>
                                            <?php $expired = (!empty($ad['ends_at']) && strtotime($ad['ends_at']) < time()); ?>
                                            <span class="badge bg-<?php echo $expired?'danger':'success'; ?>"><?php echo $expired?'Expired':'Active'; ?></span>
                                        </td>
                                        <td><?php echo date('Y-m-d H:i', strtotime($ad['created_at'])); ?></td>
                                        <td>
                                            <a href="view.php?id=<?php echo (int)$ad['id']; ?>" target="_blank" class="btn btn-sm btn-outline-secondary me-2">Preview</a>
                                            <button class="btn btn-sm btn-success me-2" onclick="approveAd(<?php echo (int)$ad['id']; ?>, 'approve')">Approve</button>
                                            <button class="btn btn-sm btn-outline-danger" onclick="approveAd(<?php echo (int)$ad['id']; ?>, 'reject')">Reject</button>
                                        </td>
                                    </tr>
                                <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <?php 
            $approvalHistory = [];
            $tblh = fetchRow("SHOW TABLES LIKE 'ad_approval_history'");
            if ($tblh) {
                $approvalHistory = fetchRows("SELECT h.*, a.title, u.full_name AS approver_name FROM ad_approval_history h JOIN ads a ON a.id=h.ad_id LEFT JOIN users u ON u.id=h.by_user_id ORDER BY h.created_at DESC LIMIT 50");
            }
            ?>
            <?php if (!empty($approvalHistory)): ?>
            <div class="card mb-4">
                <div class="card-header">Recent Approval History</div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-striped mb-0">
                            <thead>
                                <tr>
                                    <th>Advert</th>
                                    <th>Action</th>
                                    <th>By</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($approvalHistory as $h): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($h['title']); ?></td>
                                    <td><span class="badge bg-<?php echo $h['action']==='approved'?'success':'danger'; ?>"><?php echo htmlspecialchars($h['action']); ?></span></td>
                                    <td><?php echo htmlspecialchars($h['approver_name'] ?? ''); ?></td>
                                    <td><?php echo date('Y-m-d H:i', strtotime($h['created_at'])); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </main>
    </div>
</div>
<script>
async function approveAd(adId, action) {
    if (!confirm('Are you sure you want to ' + action + ' this advert?')) return;
    const formData = new FormData();
    formData.append('ad_id', adId);
    formData.append('action', action);
    try {
        const res = await fetch('ajax/approve_ad.php', { method: 'POST', body: formData });
        const data = await res.json();
        if (data.success) {
            location.reload();
        } else {
            alert(data.message || 'Operation failed');
        }
    } catch (e) {
        alert('Network error');
    }
}
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
</body>
</html>
