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

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    header('Location: my-ads.php');
    exit;
}

$ad = fetchRow("SELECT * FROM ads WHERE id=?", [$id]);
if (!$ad) {
    header('Location: my-ads.php');
    exit;
}

// Permission: creator or admin
if ($ad['created_by'] != $_SESSION['user_id'] && !hasRole(['admin'])) {
    header('Location: ../access-denied.php');
    exit;
}

// Cannot edit once fully approved
if ($ad['status'] === 'approved' || $ad['workflow_state'] === 'approved') {
    header('Location: my-ads.php');
    exit;
}

$errors = [];
$success = false;

$title = $ad['title'] ?? '';
$description = $ad['description'] ?? '';
$link_url = $ad['link_url'] ?? '';
$price = (string)($ad['price'] ?? '0');
$contact_phone = $ad['contact_phone'] ?? '';
$starts_at = $ad['starts_at'] ? date('Y-m-d\TH:i', strtotime($ad['starts_at'])) : '';
$ends_at = $ad['ends_at'] ? date('Y-m-d\TH:i', strtotime($ad['ends_at'])) : '';
$category_id = (int)($ad['category_id'] ?? 0);
$old_image = $ad['image_path'] ?? '';

$categories = [];
$tbl = fetchRow("SHOW TABLES LIKE 'ad_categories'");
if ($tbl) {
    $categories = fetchRows("SELECT id, name FROM ad_categories ORDER BY name");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $link_url = trim($_POST['link_url'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $category_id = isset($_POST['category_id']) ? (int)$_POST['category_id'] : 0;
    $price_in = trim($_POST['price'] ?? '0');
    $starts_at = trim($_POST['starts_at'] ?? '');
    $ends_at = trim($_POST['ends_at'] ?? '');
    $contact_phone = trim($_POST['contact_phone'] ?? '');

    if ($title === '') { $errors[] = 'Title is required'; }
    if ($contact_phone === '') { $errors[] = 'Phone number is required'; }
    if ($description === '') { $errors[] = 'Description is required'; }
    if ($price_in !== '' && !is_numeric($price_in)) { $errors[] = 'Price must be a number'; }
    if ($starts_at !== '' && strtotime($starts_at) === false) { $errors[] = 'Invalid start date'; }
    if ($ends_at !== '' && strtotime($ends_at) === false) { $errors[] = 'Invalid end date'; }
    if ($link_url !== '' && !filter_var($link_url, FILTER_VALIDATE_URL)) { $errors[] = 'Invalid destination link URL'; }

    // If already paid, price cannot be changed
    if ($ad['payment_status'] === 'paid' && (float)$price_in !== (float)$ad['price']) {
        $errors[] = 'Price cannot be changed after payment.';
    }

    $newImage = $old_image;
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $maxSize = 5 * 1024 * 1024;
        if (!isset($_FILES['image']['size']) || $_FILES['image']['size'] <= 0) {
            $errors[] = 'Invalid image upload';
        } elseif ($_FILES['image']['size'] > $maxSize) {
            $errors[] = 'Image is too large (max 5MB)';
        }
        $imgExt = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        $allowedExt = ['jpg','jpeg','png','gif'];
        $allowedMime = ['image/jpeg','image/png','image/gif'];
        $mime = '';
        if (function_exists('finfo_open')) {
            $f = finfo_open(FILEINFO_MIME_TYPE);
            if ($f) { $mime = finfo_file($f, $_FILES['image']['tmp_name']); finfo_close($f); }
        }
        $isImage = in_array($imgExt, $allowedExt, true) && ($mime === '' || in_array($mime, $allowedMime, true));
        if (!$isImage) { $errors[] = 'Invalid image type'; }
        if (empty($errors)) {
            $dir = __DIR__ . '/../uploads/ads/';
            if (!file_exists($dir)) { @mkdir($dir, 0777, true); }
            $fileName = 'ad_' . time() . '_' . bin2hex(random_bytes(3)) . '.' . $imgExt;
            if (!move_uploaded_file($_FILES['image']['tmp_name'], $dir . $fileName)) {
                $errors[] = 'Failed to upload ad image';
            } else {
                $newImage = $fileName;
            }
        }
    }

    if (empty($errors)) {
        $ok = executeQuery(
            "UPDATE ads SET title=?, category_id=?, description=?, link_url=?, image_path=?, contact_phone=?, starts_at=?, ends_at=?" .
            (($ad['payment_status'] !== 'paid') ? ", price=?" : "") .
            " WHERE id=?",
            ($ad['payment_status'] !== 'paid')
                ? [ $title, ($category_id?:null), $description, ($link_url?:null), $newImage, $contact_phone, ($starts_at?:null), ($ends_at?:null), (float)$price_in, (int)$id ]
                : [ $title, ($category_id?:null), $description, ($link_url?:null), $newImage, $contact_phone, ($starts_at?:null), ($ends_at?:null), (int)$id ]
        );
        if ($ok) {
            if ($newImage && $newImage !== $old_image && $old_image && preg_match('/^[\w\-.]+$/', $old_image)) {
                $old = __DIR__ . '/../uploads/ads/' . $old_image;
                if (is_file($old)) { @unlink($old); }
            }
            header('Location: my-ads.php?updated=1');
            exit;
        } else {
            $errors[] = 'Database error while updating advertisement';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Advertisement - 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">Edit Advertisement</h1>
                <a href="my-ads.php" class="btn btn-secondary">Back</a>
            </div>
            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $e): ?><li><?php echo htmlspecialchars($e); ?></li><?php endforeach; ?></ul></div>
            <?php endif; ?>
            <div class="card">
                <div class="card-body">
                    <form method="post" enctype="multipart/form-data">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Title</label>
                                <input type="text" name="title" class="form-control" value="<?php echo htmlspecialchars($title); ?>" required>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Description</label>
                                <textarea name="description" class="form-control" rows="4" required><?php echo htmlspecialchars($description); ?></textarea>
                            </div>
                            <?php if (!empty($categories)): ?>
                            <div class="col-md-6">
                                <label class="form-label">Category</label>
                                <select name="category_id" class="form-select">
                                    <option value="0">Select category</option>
                                    <?php foreach ($categories as $c): ?>
                                        <option value="<?php echo (int)$c['id']; ?>" <?php echo ($category_id==(int)$c['id'])?'selected':''; ?>><?php echo htmlspecialchars($c['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <?php endif; ?>
                            <div class="col-md-6">
                                <label class="form-label">Destination Link (optional)</label>
                                <input type="url" name="link_url" class="form-control" placeholder="https://example.com" value="<?php echo htmlspecialchars($link_url); ?>">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Phone Number</label>
                                <input type="tel" name="contact_phone" class="form-control" value="<?php echo htmlspecialchars($contact_phone); ?>" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Price (GH₵)</label>
                                <input type="number" step="0.01" name="price" class="form-control" value="<?php echo htmlspecialchars($price); ?>" <?php echo $ad['payment_status']==='paid'?'readonly':''; ?>>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Starts At (optional)</label>
                                <input type="datetime-local" name="starts_at" class="form-control" value="<?php echo htmlspecialchars($starts_at); ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Ends At (optional)</label>
                                <input type="datetime-local" name="ends_at" class="form-control" value="<?php echo htmlspecialchars($ends_at); ?>">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Ad Image (leave blank to keep current)</label>
                                <input type="file" name="image" class="form-control" accept="image/*">
                            </div>
                            <div class="col-12 mt-3">
                                <button class="btn btn-primary" type="submit">Save Changes</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
