<?php
/**
 * العروض الموسمية - حزم وخصومات لفترات محددة
 */
use App\Core\Auth;
use App\Core\Tenant;

$tenantId = Tenant::id();
$action = $_GET['action'] ?? 'index';

if (!($auth instanceof Auth) || !$auth->can('billing.view')) {
    http_response_code(403);
    echo 'غير مسموح';
    return;
}

$pkgTenant = '';
try { $db->query('SELECT tenant_id FROM test_packages LIMIT 1'); $pkgTenant = ' AND tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
$offTenant = '';
try { $db->query('SELECT tenant_id FROM seasonal_offers LIMIT 1'); $offTenant = ' AND tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}

if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST' && $auth->can('billing.create')) {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
        try {
            $db->prepare('DELETE FROM seasonal_offers WHERE id = ?')->execute([$id]);
            $_SESSION['offers_msg'] = 'تم حذف العرض.';
        } catch (Throwable $e) {}
    }
    header('Location: index.php?page=offers');
    exit;
}

if ($action === 'save' && $_SERVER['REQUEST_METHOD'] === 'POST' && $auth->can('billing.create')) {
    $id = (int)($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $desc = trim($_POST['description'] ?? '');
    $start = trim($_POST['start_date'] ?? '');
    $end = trim($_POST['end_date'] ?? '');
    $packageId = (int)($_POST['package_id'] ?? 0) ?: null;
    $discountPct = trim($_POST['discount_percent'] ?? '') !== '' ? (float)$_POST['discount_percent'] : null;
    $discountFixed = trim($_POST['discount_fixed'] ?? '') !== '' ? (float)$_POST['discount_fixed'] : null;
    if ($name !== '' && $start !== '' && $end !== '') {
        try {
            if ($id > 0) {
                $db->prepare('UPDATE seasonal_offers SET name=?, description=?, start_date=?, end_date=?, package_id=?, discount_percent=?, discount_fixed=?, is_active=1 WHERE id=?')->execute([$name, $desc ?: null, $start, $end, $packageId, $discountPct, $discountFixed, $id]);
            } else {
                try {
                    $db->prepare('INSERT INTO seasonal_offers (name, description, start_date, end_date, package_id, discount_percent, discount_fixed, tenant_id) VALUES (?,?,?,?,?,?,?,?)')->execute([$name, $desc ?: null, $start, $end, $packageId, $discountPct, $discountFixed, $tenantId]);
                } catch (Throwable $e) {
                    $db->prepare('INSERT INTO seasonal_offers (name, description, start_date, end_date, package_id, discount_percent, discount_fixed) VALUES (?,?,?,?,?,?,?)')->execute([$name, $desc ?: null, $start, $end, $packageId, $discountPct, $discountFixed]);
                }
            }
            $_SESSION['offers_msg'] = 'تم حفظ العرض.';
        } catch (Throwable $e) {}
    }
    header('Location: index.php?page=offers');
    exit;
}

$packages = [];
try {
    $db->query('SELECT id FROM test_packages LIMIT 1');
    $stmt = $db->query('SELECT id, name, price FROM test_packages WHERE is_active = 1' . $pkgTenant . ' ORDER BY name');
    $packages = $stmt->fetchAll();
} catch (Throwable $e) {}

$offers = [];
try {
    $db->query('SELECT id FROM seasonal_offers LIMIT 1');
    $stmt = $db->prepare('SELECT o.*, p.name AS package_name FROM seasonal_offers o LEFT JOIN test_packages p ON p.id = o.package_id WHERE (o.tenant_id = ? OR o.tenant_id IS NULL) ORDER BY o.start_date DESC');
    $stmt->execute([$tenantId]);
    $offers = $stmt->fetchAll();
} catch (Throwable $e) {
    try {
        $stmt = $db->query('SELECT o.*, p.name AS package_name FROM seasonal_offers o LEFT JOIN test_packages p ON p.id = o.package_id ORDER BY o.start_date DESC');
        $offers = $stmt->fetchAll();
    } catch (Throwable $e2) {}
}

$now = date('Y-m-d');
$statsOffers = ['active' => 0, 'upcoming' => 0, 'expired' => 0];
foreach ($offers as $o) {
    if ($o['end_date'] < $now) $statsOffers['expired']++;
    elseif ($o['start_date'] <= $now) $statsOffers['active']++;
    else $statsOffers['upcoming']++;
}

$filterStatus = trim($_GET['status'] ?? '');
$filteredOffers = $offers;
if ($filterStatus === 'active') $filteredOffers = array_filter($offers, fn($o) => $o['start_date'] <= $now && $o['end_date'] >= $now);
elseif ($filterStatus === 'upcoming') $filteredOffers = array_filter($offers, fn($o) => $o['start_date'] > $now);
elseif ($filterStatus === 'expired') $filteredOffers = array_filter($offers, fn($o) => $o['end_date'] < $now);
$filteredOffers = array_values($filteredOffers);
?>
<div class="offers-page">
<div class="page-header">
    <h1>عروض موسمية</h1>
    <?php if ($auth->can('billing.create')): ?><a href="index.php?page=offers&action=edit" class="btn-primary">+ عرض جديد</a><?php endif; ?>
</div>
<?php if (!empty($_SESSION['offers_msg'])): ?><div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['offers_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['offers_msg']); ?></div><?php endif; ?>

<?php if ($action === 'edit'): ?>
<?php $editId = (int)($_GET['id'] ?? 0); $edit = null; foreach ($offers as $o) { if ((int)$o['id'] === $editId) { $edit = $o; break; } } ?>
<div class="section-card">
    <h3><?php echo $edit ? 'تعديل العرض' : 'عرض جديد'; ?></h3>
    <form method="post" action="index.php?page=offers&action=save" class="form-grid">
        <input type="hidden" name="id" value="<?php echo $edit ? (int)$edit['id'] : 0; ?>">
        <div>
            <label>اسم العرض *</label>
            <input type="text" name="name" required value="<?php echo htmlspecialchars($edit['name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="مثال: عرض رمضان">
        </div>
        <div class="full-width">
            <label>الوصف</label>
            <textarea name="description" rows="2" placeholder="وصف مختصر للعرض"><?php echo htmlspecialchars($edit['description'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
        </div>
        <div>
            <label>من تاريخ *</label>
            <input type="date" name="start_date" required value="<?php echo htmlspecialchars($edit['start_date'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>إلى تاريخ *</label>
            <input type="date" name="end_date" required value="<?php echo htmlspecialchars($edit['end_date'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>الحزمة المرتبطة</label>
            <select name="package_id">
                <option value="">— بدون ربط —</option>
                <?php foreach ($packages as $p): ?>
                <option value="<?php echo (int)$p['id']; ?>" <?php echo $edit && (int)($edit['package_id'] ?? 0) === (int)$p['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($p['name'], ENT_QUOTES, 'UTF-8'); ?> — <?php echo number_format($p['price'] ?? 0); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>خصم %</label>
            <input type="number" step="0.01" min="0" max="100" name="discount_percent" value="<?php echo htmlspecialchars($edit['discount_percent'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="مثال: 10">
        </div>
        <div>
            <label>خصم ثابت (مبلغ)</label>
            <input type="number" step="0.01" min="0" name="discount_fixed" value="<?php echo htmlspecialchars($edit['discount_fixed'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="مثال: 5000">
        </div>
        <div class="full-width form-actions">
            <button type="submit" class="btn-primary">حفظ</button>
            <a href="index.php?page=offers" class="btn-secondary">إلغاء</a>
        </div>
    </form>
</div>
<?php else: ?>
<?php if (!empty($offers)): ?>
<div class="stats-cards offers-stats" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:12px;margin-bottom:20px;">
    <div class="stat-card" style="background:var(--bg-card);border:1px solid var(--border);border-radius:8px;padding:14px;">
        <div style="color:var(--text-muted);font-size:0.85em;">نشط</div>
        <div style="font-size:1.5em;font-weight:600;color:var(--success);"><?php echo $statsOffers['active']; ?></div>
    </div>
    <div class="stat-card" style="background:var(--bg-card);border:1px solid var(--border);border-radius:8px;padding:14px;">
        <div style="color:var(--text-muted);font-size:0.85em;">قادم</div>
        <div style="font-size:1.5em;font-weight:600;color:var(--primary);"><?php echo $statsOffers['upcoming']; ?></div>
    </div>
    <div class="stat-card" style="background:var(--bg-card);border:1px solid var(--border);border-radius:8px;padding:14px;">
        <div style="color:var(--text-muted);font-size:0.85em;">منتهي</div>
        <div style="font-size:1.5em;font-weight:600;color:var(--text-muted);"><?php echo $statsOffers['expired']; ?></div>
    </div>
</div>
<form method="get" class="offers-filters" style="display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-bottom:16px;">
    <input type="hidden" name="page" value="offers">
    <select name="status" onchange="this.form.submit()" style="padding:10px 14px;border:1px solid var(--border);border-radius:var(--radius-sm);">
        <option value="">كل العروض</option>
        <option value="active" <?php echo $filterStatus === 'active' ? 'selected' : ''; ?>>نشط فقط</option>
        <option value="upcoming" <?php echo $filterStatus === 'upcoming' ? 'selected' : ''; ?>>قادم فقط</option>
        <option value="expired" <?php echo $filterStatus === 'expired' ? 'selected' : ''; ?>>منتهي فقط</option>
    </select>
</form>
<?php endif; ?>
<div class="section-card">
    <?php if (empty($offers)): ?>
    <div class="offers-empty-state">
        <div class="offers-empty-icon">🎁</div>
        <h3 class="offers-empty-title">لا توجد عروض موسمية</h3>
        <p class="offers-empty-desc">أنشئ عروضاً موسمية لربطها بحزم الفحوصات وتقديم خصومات لفترة محددة.</p>
        <?php if ($auth->can('billing.create')): ?>
        <a href="index.php?page=offers&action=edit" class="btn-primary">إنشاء أول عرض</a>
        <?php endif; ?>
    </div>
    <?php elseif (empty($filteredOffers)): ?>
    <div class="offers-empty-filtered">
        <p>لا توجد عروض مطابقة للفلتر.</p>
        <a href="index.php?page=offers" class="btn-secondary" style="display:inline-block;margin-top:12px;">عرض الكل</a>
    </div>
    <?php else: ?>
    <div class="table-wrapper offers-table-wrapper">
        <table class="table">
            <thead>
                <tr>
                    <th>العرض</th>
                    <th>الفترة</th>
                    <th>الحزمة</th>
                    <th>الخصم</th>
                    <th>الإجراءات</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($filteredOffers as $o): $active = $o['start_date'] <= $now && $o['end_date'] >= $now; $expired = $o['end_date'] < $now; ?>
            <tr class="<?php echo $expired ? 'offers-row-expired' : ''; ?>">
                <td class="offers-cell-name">
                    <div class="offers-name-row">
                        <strong><?php echo htmlspecialchars($o['name'], ENT_QUOTES, 'UTF-8'); ?></strong>
                        <?php if ($active): ?><span class="badge badge-validated">نشط</span>
                        <?php elseif ($expired): ?><span class="badge badge-cancelled">منتهي</span>
                        <?php else: ?><span class="badge badge-pending">قادم</span><?php endif; ?>
                    </div>
                    <?php if (!empty($o['description'])): ?>
                    <small class="offers-desc"><?php echo htmlspecialchars(mb_substr($o['description'], 0, 60) . (mb_strlen($o['description']) > 60 ? '...' : ''), ENT_QUOTES, 'UTF-8'); ?></small>
                    <?php endif; ?>
                </td>
                <td class="offers-cell-period"><?php echo htmlspecialchars(date('d/m/Y', strtotime($o['start_date'])) . ' ← ' . date('d/m/Y', strtotime($o['end_date'])), ENT_QUOTES, 'UTF-8'); ?></td>
                <td><?php echo htmlspecialchars($o['package_name'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></td>
                <td>
                    <?php if ($o['discount_percent']): ?>
                    <span class="offers-discount"><?php echo htmlspecialchars($o['discount_percent'], ENT_QUOTES, 'UTF-8'); ?>%</span>
                    <?php elseif ($o['discount_fixed']): ?>
                    <span class="offers-discount"><?php echo number_format($o['discount_fixed']); ?></span>
                    <?php else: ?>—<?php endif; ?>
                </td>
                <td>
                    <?php if ($auth->can('billing.create')): ?>
                    <div class="offers-row-actions">
                        <a href="index.php?page=offers&action=edit&id=<?php echo (int)$o['id']; ?>" class="btn-action btn-action--edit">تعديل</a>
                        <form method="post" action="index.php?page=offers&action=delete" style="display:inline;" onsubmit="return confirm('حذف هذا العرض؟');">
                            <input type="hidden" name="id" value="<?php echo (int)$o['id']; ?>">
                            <button type="submit" class="btn-action btn-action--delete">حذف</button>
                        </form>
                    </div>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>
</div>
