<?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 = '..';

$userId = $_SESSION['user_id'];
$ads = fetchRows(
    "SELECT a.*, c.name AS category_name
     FROM ads a
     LEFT JOIN ad_categories c ON a.category_id = c.id
     WHERE a.created_by = ?
     ORDER BY a.created_at DESC",
    [$userId]
);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My 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">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
</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">My Adverts</h1>
                <a href="submit.php" class="btn btn-primary"><i class="fas fa-plus me-2"></i>Submit New Advert</a>
            </div>

            <div class="card">
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-striped mb-0 align-middle">
                            <thead>
                                <tr>
                                    <th style="width:100px;">Image</th>
                                    <th>Title</th>
                                    <th>Category</th>
                                    <th>Price</th>
                                    <th>Payment</th>
                                    <th>Status</th>
                                    <th>Workflow</th>
                                    <th>Created</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($ads)): ?>
                                    <tr><td colspan="9" class="text-center text-muted py-4">You have not submitted any adverts yet.</td></tr>
                                <?php else: foreach ($ads as $ad): ?>
                                    <tr>
                                        <td>
                                            <div class="ratio ratio-4x3" style="width: 100px;">
                                                <img src="<?php echo $basePath; ?>/uploads/ads/<?php echo htmlspecialchars($ad['image_path']); ?>" alt="<?php echo htmlspecialchars($ad['title']); ?>" class="img-fluid" style="object-fit:cover;">
                                            </div>
                                        </td>
                                        <td><?php echo htmlspecialchars($ad['title']); ?></td>
                                        <td><?php echo htmlspecialchars($ad['category_name'] ?? ''); ?></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':($ad['payment_status']==='failed'?'danger':'warning')); ?>">
                                                <?php echo htmlspecialchars($ad['payment_status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?php echo $ad['status']==='approved'?'success':($ad['status']==='rejected'?'danger':'warning'); ?>">
                                                <?php echo htmlspecialchars($ad['status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?php echo $ad['workflow_state']==='approved'?'success':($ad['workflow_state']==='rejected'?'danger':($ad['workflow_state']==='pending_approval'?'info':'secondary')); ?>">
                                                <?php echo htmlspecialchars($ad['workflow_state']); ?>
                                            </span>
                                        </td>
                                        <td><?php echo date('Y-m-d H:i', strtotime($ad['created_at'])); ?></td>
                                        <td class="text-nowrap">
                                            <?php if ($ad['workflow_state']==='payment_pending' && $ad['status']==='pending' && (float)$ad['price'] > 0 && $ad['payment_status'] !== 'paid'): ?>
                                                <a href="pay.php?ad_id=<?php echo (int)$ad['id']; ?>" class="btn btn-sm btn-primary me-1">Pay</a>
                                            <?php endif; ?>
                                            <a href="view.php?id=<?php echo (int)$ad['id']; ?>" class="btn btn-sm btn-outline-secondary me-1">Preview</a>
                                            <?php if ($ad['status']==='approved'): ?>
                                                <a href="view.php?id=<?php echo (int)$ad['id']; ?>" class="btn btn-sm btn-success me-1">Public Link</a>
                                            <?php endif; ?>
                                            <?php if ($ad['status']!=='approved'): ?>
                                                <a href="edit.php?id=<?php echo (int)$ad['id']; ?>" class="btn btn-sm btn-warning me-1">Edit</a>
                                                <button class="btn btn-sm btn-outline-danger" onclick="deleteAd(<?php echo (int)$ad['id']; ?>)">Delete</button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>
<script>
async function deleteAd(adId) {
    if (!confirm('Delete this advert? This action cannot be undone.')) return;
    const formData = new FormData();
    formData.append('ad_id', adId);
    try {
        const res = await fetch('ajax/delete_ad.php', { method: 'POST', body: formData });
        const data = await res.json();
        if (data.success) {
            location.reload();
        } else {
            alert(data.message || 'Delete 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>
</body>
</html>
