<?php
require_once __DIR__ . '/../app/csrf.php';
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/csrf.php';

$me  = require_role(['ADMIN','WAREHOUSE']);
$pdo = db();

$pageError   = '';
$pageSuccess = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $op = $_POST['op'] ?? '';

    if ($op === 'create') {
        $pid = (int)($_POST['product_id']   ?? 0);
        $m   = (int)($_POST['month']        ?? 0);
        $y   = (int)($_POST['year']         ?? 0);
        $num = (int)($_POST['issue_number'] ?? 0);
        $pr  = (float)($_POST['price']      ?? 0);
        if ($pid <= 0 || $m < 1 || $m > 12 || $y < 2000) {
            $pageError = 'يرجى تعبئة جميع الحقول بشكل صحيح.';
        } else {
            try {
                $pdo->prepare("
                    INSERT INTO issues
                        (product_id, issue_month, issue_year, issue_number, cover_price, status)
                    VALUES (?,?,?,?,?,'OPEN')
                ")->execute([$pid, $m, $y, $num > 0 ? $num : null, $pr]);
                $pageSuccess = 'تم إضافة الإصدار بنجاح.';
            } catch (Throwable $e) {
                $pageError = 'خطأ: ' . $e->getMessage();
            }
        }
    }

    if ($op === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        try {
            $pdo->prepare("UPDATE issues SET status = IF(status='OPEN','CLOSED','OPEN') WHERE id=?")
                ->execute([$id]);
            $pageSuccess = 'تم تغيير حالة الإصدار.';
        } catch (Throwable $e) {
            $pageError = 'خطأ: ' . $e->getMessage();
        }
    }

    if ($op === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        try {
            $checks = [
                'warehouse_receipt_items'    => 'توريدات مخزن',
                'distributor_dispatch_items' => 'صرف موزعين',
                'warehouse_return_items'     => 'مرتجعات',
                'outlet_delivery_items'      => 'شحن منافذ',
                'outlet_settlement_lines'    => 'تسويات',
                'invoice_items'              => 'فواتير',
            ];
            $linked = [];
            foreach ($checks as $table => $label) {
                $cnt = $pdo->prepare("SELECT COUNT(*) FROM `$table` WHERE issue_id = ?");
                $cnt->execute([$id]);
                if ((int)$cnt->fetchColumn() > 0) $linked[] = $label;
            }
            if (!empty($linked)) {
                $pageError = 'لا يمكن حذف هذا الإصدار لأنه مرتبط بـ: ' . implode('، ', $linked);
            } else {
                $pdo->prepare("DELETE FROM issues WHERE id = ?")->execute([$id]);
                $pageSuccess = 'تم حذف الإصدار بنجاح.';
            }
        } catch (Throwable $e) {
            $pageError = 'خطأ أثناء الحذف: ' . $e->getMessage();
        }
    }
}

$prods  = $pdo->query("SELECT id, name FROM products ORDER BY name")->fetchAll();
$issues = $pdo->query("
    SELECT i.*, p.name AS product_name
    FROM issues i
    JOIN products p ON p.id = i.product_id
    ORDER BY i.issue_year DESC, i.issue_month DESC, i.issue_number DESC
")->fetchAll();

$csrf = csrf_token();
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>إدارة الإصدارات — MGZ</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
    font-family: 'Tajawal', sans-serif;
    background: #f4f7f6;
    direction: rtl;
    padding: 20px;
    font-size: 14px;
}
a { color: #1a73e8; text-decoration: none; }
a:hover { text-decoration: underline; }
.back-link { margin-bottom: 14px; display: inline-block; }
.page-header {
    background: linear-gradient(135deg, #1a73e8, #0d47a1);
    color: #fff;
    padding: 18px 24px;
    border-radius: 10px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.page-header h2 { font-size: 1.2rem; font-weight: 700; }
.card {
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
    margin-bottom: 20px;
    overflow: hidden;
}
.card-header {
    padding: 14px 20px;
    border-bottom: 1px solid #eee;
    font-weight: 700;
    background: #fafafa;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.card-body { padding: 20px; }
.form-grid {
    display: grid;
    grid-template-columns: 2fr 1fr 1fr 1fr 1fr auto;
    gap: 12px;
    align-items: end;
}
.form-group label {
    display: block;
    font-weight: 600;
    color: #555;
    margin-bottom: 5px;
    font-size: .85rem;
}
input[type=number], select {
    width: 100%;
    padding: 8px 10px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: .9rem;
    font-family: inherit;
    background: #fff;
}
input:focus, select:focus {
    outline: none;
    border-color: #1a73e8;
    box-shadow: 0 0 0 3px rgba(26,115,232,.1);
}
.btn {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 8px 16px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: .88rem;
    font-family: inherit;
    font-weight: 600;
    white-space: nowrap;
    transition: opacity .15s;
}
.btn:hover { opacity: .88; }
.btn-primary { background: #1a73e8; color: #fff; }
.btn-danger  { background: #ea4335; color: #fff; }
.btn-warning { background: #fbbc04; color: #333; }
.btn-sm { padding: 4px 10px; font-size: .8rem; }
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; }
th, td {
    padding: 10px 14px;
    border-bottom: 1px solid #eee;
    text-align: right;
    white-space: nowrap;
}
th { background: #f8f9fa; font-weight: 600; color: #555; font-size: .85rem; }
tr:last-child td { border-bottom: none; }
tbody tr:hover td { background: #fafbff; }
.alert {
    padding: 12px 16px;
    border-radius: 7px;
    margin-bottom: 16px;
    font-size: .9rem;
}
.alert-danger  { background: #fce8e6; color: #c62828; border-right: 4px solid #ea4335; }
.alert-success { background: #e6f4ea; color: #1e7e34; border-right: 4px solid #34a853; }
.alert-info    { background: #e3f2fd; color: #0d47a1; border-right: 4px solid #1a73e8; }
.badge-open   { background: #e6f4ea; color: #1e7e34; padding: 3px 12px; border-radius: 20px; font-size: .78rem; font-weight: 700; }
.badge-closed { background: #fce8e6; color: #c62828; padding: 3px 12px; border-radius: 20px; font-size: .78rem; font-weight: 700; }
.issue-num    { background: #e8f0fe; color: #1a73e8; padding: 2px 10px; border-radius: 12px; font-size: .82rem; font-weight: 700; }
.empty-state  { text-align: center; padding: 40px 20px; color: #aaa; }
@media (max-width: 900px) {
    .form-grid { grid-template-columns: 1fr 1fr; }
    body { padding: 12px; }
}
@media (max-width: 500px) {
    .form-grid { grid-template-columns: 1fr; }
}
</style>
</head>
<body>

<a href="../dashboard.php" class="back-link">&#8594; العودة للرئيسية</a>

<div class="page-header">
    <h2>&#128240; إدارة الإصدارات</h2>
    <a href="products.php" style="color:rgba(255,255,255,.8);font-size:.85rem;">
        &#128218; إدارة المنتجات
    </a>
</div>

<?php if ($pageError !== ''): ?>
<div class="alert alert-danger">&#9888; <?= htmlspecialchars($pageError) ?></div>
<?php endif; ?>
<?php if ($pageSuccess !== ''): ?>
<div class="alert alert-success">&#9989; <?= htmlspecialchars($pageSuccess) ?></div>
<?php endif; ?>

<div class="card">
    <div class="card-header">&#43; إضافة إصدار جديد</div>
    <div class="card-body">
        <?php if (empty($prods)): ?>
        <div class="alert alert-info">
            &#8505; لا توجد منتجات —
            <a href="products.php">أضف منتجاً أولاً</a>
        </div>
        <?php else: ?>
        <form method="post">
            <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
            <input type="hidden" name="op"   value="create">
            <div class="form-grid">
                <div class="form-group">
                    <label>المنتج *</label>
                    <select name="product_id" required>
                        <option value="">— اختر المنتج —</option>
                        <?php foreach ($prods as $p): ?>
                        <option value="<?= (int)$p['id'] ?>"><?= h($p['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>الشهر *</label>
                    <input type="number" name="month"
                           placeholder="1-12"
                           min="1" max="12"
                           value="<?= date('n') ?>" required>
                </div>
                <div class="form-group">
                    <label>السنة *</label>
                    <input type="number" name="year"
                           placeholder="2026"
                           min="2000"
                           value="<?= date('Y') ?>" required>
                </div>
                <div class="form-group">
                    <label>رقم العدد</label>
                    <input type="number" name="issue_number"
                           placeholder="مثال: 145"
                           min="1">
                </div>
                <div class="form-group">
                    <label>سعر الغلاف (ر.ع.) *</label>
                    <input type="number" name="price"
                           placeholder="0.000"
                           step="0.001" min="0" required>
                </div>
                <div class="form-group">
                    <label>&nbsp;</label>
                    <button type="submit" class="btn btn-primary">&#10003; حفظ</button>
                </div>
            </div>
        </form>
        <?php endif; ?>
    </div>
</div>

<div class="card">
    <div class="card-header">
        قائمة الإصدارات
        <span style="font-weight:400;font-size:.85rem;color:#888;"><?= count($issues) ?> إصدار</span>
    </div>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>المنتج</th>
                    <th>رقم العدد</th>
                    <th>الشهر / السنة</th>
                    <th>سعر الغلاف</th>
                    <th>الحالة</th>
                    <th>تغيير الحالة</th>
                    <th>حذف</th>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($issues)): ?>
                <tr><td colspan="8">
                    <div class="empty-state">لا توجد إصدارات بعد — أضف إصداراً من الأعلى</div>
                </td></tr>
            <?php else: ?>
                <?php foreach ($issues as $idx => $i): ?>
                <tr>
                    <td><?= $idx + 1 ?></td>
                    <td><strong><?= h($i['product_name']) ?></strong></td>
                    <td>
                        <?php if (!empty($i['issue_number'])): ?>
                        <span class="issue-num">عدد <?= (int)$i['issue_number'] ?></span>
                        <?php else: ?>
                        <span style="color:#aaa;">—</span>
                        <?php endif; ?>
                    
                    </td>
                    <td><?= str_pad((int)$i['issue_month'], 2, '0', STR_PAD_LEFT) ?>/<?= (int)$i['issue_year'] ?></td>
                    <td><?= omr((float)$i['cover_price']) ?></td>
                    <td>
                        <span class="<?= $i['status']==='OPEN' ? 'badge-open' : 'badge-closed' ?>">
                            <?= $i['status']==='OPEN' ? 'مفتوح' : 'مغلق' ?>
                        </span>
                    </td>
                    <td>
                        <form method="post" style="display:inline">
                            <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
                            <input type="hidden" name="op"   value="toggle">
                            <input type="hidden" name="id"   value="<?= (int)$i['id'] ?>">
                            <button type="submit" class="btn btn-warning btn-sm">&#8645; تغيير</button>
                        </form>
                    </td>
                    <td>
                        <form method="post" style="display:inline"
                              onsubmit="return confirm('حذف هذا الإصدار نهائياً؟')">
                            <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
                            <input type="hidden" name="op"   value="delete">
                            <input type="hidden" name="id"   value="<?= (int)$i['id'] ?>">
                            <button type="submit" class="btn btn-danger btn-sm">&#128465; حذف</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

</body>
</html>
