<?php

use App\Core\Auth;
use App\Core\Tenant;

require_once __DIR__ . '/../src/Core/CSRFProtection.php';

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

if (!($auth instanceof Auth) || !$auth->can('inventory.view')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى هذه الصفحة';
    return;
}

$canManage = ($auth instanceof Auth) && $auth->can('inventory.manage');

// إنشاء مادة
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF Protection
    if (!\App\Core\CSRFProtection::validatePostRequest()) {
        $_SESSION['inventory_error'] = 'طلب غير صالح.';
        header('Location: index.php?page=inventory');
        exit;
    }
    if (!$canManage) {
        http_response_code(403);
        echo 'غير مسموح بإدارة المخزون';
        return;
    }
    $name = trim($_POST['name'] ?? '');
    $code = trim($_POST['item_code'] ?? '');
    $unit = trim($_POST['unit'] ?? '');
    $minQty = (float)($_POST['min_quantity'] ?? 0);
    $currentQty = (float)($_POST['current_quantity'] ?? 0);

    if ($name !== '' && $code !== '') {
        $expiry = trim($_POST['expiry_date'] ?? '') ?: null;
        $batch = trim($_POST['batch_number'] ?? '') ?: null;
        try {
            $db->query('SELECT tenant_id FROM inventory_items LIMIT 1');
            try {
                $db->query('SELECT expiry_date FROM inventory_items LIMIT 1');
                $stmt = $db->prepare('INSERT INTO inventory_items (item_code, name, unit, min_quantity, current_quantity, expiry_date, batch_number, tenant_id) VALUES (?,?,?,?,?,?,?,?)');
                $stmt->execute([$code, $name, $unit ?: null, $minQty, $currentQty, $expiry, $batch, $tenantId]);
            } catch (Throwable $e2) {
                $stmt = $db->prepare('INSERT INTO inventory_items (item_code, name, unit, min_quantity, current_quantity, tenant_id) VALUES (?,?,?,?,?,?)');
                $stmt->execute([$code, $name, $unit ?: null, $minQty, $currentQty, $tenantId]);
            }
        } catch (Throwable $e) {
            try {
                $db->query('SELECT expiry_date FROM inventory_items LIMIT 1');
                $stmt = $db->prepare('INSERT INTO inventory_items (item_code, name, unit, min_quantity, current_quantity, expiry_date, batch_number) VALUES (?,?,?,?,?,?,?)');
                $stmt->execute([$code, $name, $unit ?: null, $minQty, $currentQty, $expiry, $batch]);
            } catch (Throwable $e2) {
                $stmt = $db->prepare('INSERT INTO inventory_items (item_code, name, unit, min_quantity, current_quantity) VALUES (?,?,?,?,?)');
                $stmt->execute([$code, $name, $unit ?: null, $minQty, $currentQty]);
            }
        }
        if (isset($auditLog)) {
            $auditLog->log('inventory_item_created', 'inventory_item', (int)$db->lastInsertId(), null, json_encode(['item_code' => $code, 'name' => $name, 'unit' => $unit, 'current_quantity' => $currentQty], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
        }
    }
    header('Location: index.php?page=inventory');
    exit;
}

// تعديل مادة
if ($action === 'edit' && $_SERVER['REQUEST_METHOD'] === 'POST' && $canManage) {
    // CSRF Protection
    if (!\App\Core\CSRFProtection::validatePostRequest()) {
        $_SESSION['inventory_error'] = 'طلب غير صالح.';
        header('Location: index.php?page=inventory');
        exit;
    }
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
        $stmt = $db->prepare('SELECT id FROM inventory_items WHERE id = ? AND tenant_id = ?');
        $stmt->execute([$id, $tenantId]);
        if ($stmt->fetch()) {
            $name = trim($_POST['name'] ?? '');
            $unit = trim($_POST['unit'] ?? '');
            $minQty = (float)($_POST['min_quantity'] ?? 0);
            $currentQty = (float)($_POST['current_quantity'] ?? 0);
            $expiry = trim($_POST['expiry_date'] ?? '') ?: null;
            $batch = trim($_POST['batch_number'] ?? '') ?: null;
            if ($name !== '') {
                try {
                    $db->query('SELECT expiry_date FROM inventory_items LIMIT 1');
                    $stmt = $db->prepare('UPDATE inventory_items SET name=?, unit=?, min_quantity=?, current_quantity=?, expiry_date=?, batch_number=? WHERE id=?');
                    $stmt->execute([$name, $unit ?: null, $minQty, $currentQty, $expiry, $batch, $id]);
                } catch (Throwable $e) {
                    $stmt = $db->prepare('UPDATE inventory_items SET name=?, unit=?, min_quantity=?, current_quantity=? WHERE id=?');
                    $stmt->execute([$name, $unit ?: null, $minQty, $currentQty, $id]);
                }
                if (isset($auditLog)) {
                    $auditLog->log('inventory_item_updated', 'inventory_item', $id, null, json_encode(['name' => $name, 'current_quantity' => $currentQty], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
                }
            }
        }
    }
    header('Location: index.php?page=inventory');
    exit;
}

// ضبط الكمية
if ($action === 'adjust' && $_SERVER['REQUEST_METHOD'] === 'POST' && $canManage) {
    // CSRF Protection
    if (!\App\Core\CSRFProtection::validatePostRequest()) {
        $_SESSION['inventory_error'] = 'طلب غير صالح.';
        header('Location: index.php?page=inventory');
        exit;
    }
    $id = (int)($_POST['id'] ?? 0);
    $delta = (float)($_POST['delta'] ?? 0);
    $note = trim($_POST['note'] ?? '');
    if ($id > 0 && $delta != 0) {
        $stmt = $db->prepare('SELECT id, current_quantity FROM inventory_items WHERE id = ? AND tenant_id = ?');
        $stmt->execute([$id, $tenantId]);
        $item = $stmt->fetch();
        if ($item) {
            $newQty = (float)$item['current_quantity'] + $delta;
            if ($newQty >= 0) {
                $db->prepare('UPDATE inventory_items SET current_quantity = ? WHERE id = ?')->execute([$newQty, $id]);
                if (isset($auditLog)) {
                    $auditLog->log('inventory_adjusted', 'inventory_item', $id, json_encode(['old' => $item['current_quantity'], 'delta' => $delta], JSON_UNESCAPED_UNICODE), json_encode(['new' => $newQty, 'note' => $note], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
                }
            }
        }
    }
    header('Location: index.php?page=inventory');
    exit;
}

// نموذج الإضافة
if ($action === 'create') {
    ?>
    <div class="page-header">
        <h1>إضافة مادة مخزون</h1>
        <a href="index.php?page=inventory" class="btn-secondary">← رجوع</a>
    </div>
    <div class="card section-card">
    <form method="post" class="form-grid">
        <div>
            <label>كود المادة</label>
            <input type="text" name="item_code" required placeholder="مثال: MAT-001">
        </div>
        <div>
            <label>اسم المادة</label>
            <input type="text" name="name" required placeholder="اسم المادة">
        </div>
        <div>
            <label>الوحدة</label>
            <input type="text" name="unit" placeholder="علبة، زجاجة، مل...">
        </div>
        <div>
            <label>الكمية الحالية</label>
            <input type="number" step="0.01" name="current_quantity" value="0" min="0">
        </div>
        <div>
            <label>حد التنبيه الأدنى</label>
            <input type="number" step="0.01" name="min_quantity" value="0" min="0" placeholder="تنبيه عند انخفاض الكمية">
        </div>
        <?php try { $db->query('SELECT expiry_date FROM inventory_items LIMIT 1'); ?>
        <div><label>تاريخ الانتهاء</label><input type="date" name="expiry_date"></div>
        <div><label>رقم الدفعة</label><input type="text" name="batch_number" placeholder="اختياري"></div>
        <?php } catch (Throwable $e) {} ?>
        <div class="full-width form-actions">
            <button type="submit" class="btn-primary">حفظ</button>
            <a href="index.php?page=inventory" class="btn-secondary">إلغاء</a>
        </div>
    </form>
    </div>
    <?php
    return;
}

// نموذج التعديل
if ($action === 'edit' && isset($_GET['id'])) {
    $editId = (int)$_GET['id'];
    $stmt = $db->prepare('SELECT id, item_code, name, unit, min_quantity, current_quantity FROM inventory_items WHERE id = ? AND tenant_id = ?');
    $stmt->execute([$editId, $tenantId]);
    $editItem = $stmt->fetch();
    $editExpiry = $editBatch = null;
    try {
        $db->query('SELECT expiry_date FROM inventory_items LIMIT 1');
        $stmt = $db->prepare('SELECT expiry_date, batch_number FROM inventory_items WHERE id = ?');
        $stmt->execute([$editId]);
        $ex = $stmt->fetch();
        if ($ex) { $editExpiry = $ex['expiry_date'] ?? ''; $editBatch = $ex['batch_number'] ?? ''; }
    } catch (Throwable $e) {}
    if (!$editItem) {
        header('Location: index.php?page=inventory');
        exit;
    }
    ?>
    <div class="page-header">
        <h1>تعديل مادة: <?php echo htmlspecialchars($editItem['name'], ENT_QUOTES, 'UTF-8'); ?></h1>
        <a href="index.php?page=inventory" class="btn-secondary">← رجوع</a>
    </div>
    <div class="card section-card">
    <form method="post" class="form-grid">
        <input type="hidden" name="id" value="<?php echo (int)$editItem['id']; ?>">
        <div>
            <label>كود المادة</label>
            <input type="text" value="<?php echo htmlspecialchars($editItem['item_code'], ENT_QUOTES, 'UTF-8'); ?>" disabled style="background:#f1f5f9;">
        </div>
        <div>
            <label>اسم المادة</label>
            <input type="text" name="name" required value="<?php echo htmlspecialchars($editItem['name'], ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>الوحدة</label>
            <input type="text" name="unit" value="<?php echo htmlspecialchars($editItem['unit'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>الكمية الحالية</label>
            <input type="number" step="0.01" name="current_quantity" value="<?php echo htmlspecialchars($editItem['current_quantity'], ENT_QUOTES, 'UTF-8'); ?>" min="0">
        </div>
        <div>
            <label>حد التنبيه الأدنى</label>
            <input type="number" step="0.01" name="min_quantity" value="<?php echo htmlspecialchars($editItem['min_quantity'], ENT_QUOTES, 'UTF-8'); ?>" min="0">
        </div>
        <?php try { $db->query('SELECT expiry_date FROM inventory_items LIMIT 1'); ?>
        <div><label>تاريخ الانتهاء</label><input type="date" name="expiry_date" value="<?php echo htmlspecialchars($editExpiry ?? '', ENT_QUOTES, 'UTF-8'); ?>"></div>
        <div><label>رقم الدفعة</label><input type="text" name="batch_number" value="<?php echo htmlspecialchars($editBatch ?? '', ENT_QUOTES, 'UTF-8'); ?>"></div>
        <?php } catch (Throwable $e) {} ?>
        <div class="full-width form-actions">
            <button type="submit" class="btn-primary">حفظ التعديلات</button>
            <a href="index.php?page=inventory" class="btn-secondary">إلغاء</a>
        </div>
    </form>
    </div>
    <?php
    return;
}

// نموذج ضبط الكمية
if ($action === 'adjust' && isset($_GET['id'])) {
    $adjId = (int)$_GET['id'];
    $stmt = $db->prepare('SELECT id, item_code, name, unit, current_quantity FROM inventory_items WHERE id = ? AND tenant_id = ?');
    $stmt->execute([$adjId, $tenantId]);
    $adjItem = $stmt->fetch();
    if (!$adjItem) {
        header('Location: index.php?page=inventory');
        exit;
    }
    ?>
    <div class="page-header">
        <h1>ضبط الكمية: <?php echo htmlspecialchars($adjItem['name'], ENT_QUOTES, 'UTF-8'); ?></h1>
        <a href="index.php?page=inventory" class="btn-secondary">← رجوع</a>
    </div>
    <div class="card section-card">
    <p style="margin-bottom:16px;">الكمية الحالية: <strong><?php echo htmlspecialchars($adjItem['current_quantity'], ENT_QUOTES, 'UTF-8'); ?></strong> <?php echo htmlspecialchars($adjItem['unit'] ?? '', ENT_QUOTES, 'UTF-8'); ?></p>
    <form method="post" class="form-grid">
        <input type="hidden" name="id" value="<?php echo (int)$adjItem['id']; ?>">
        <div>
            <label>التغيير (+ إضافة / - خصم)</label>
            <input type="number" step="0.01" name="delta" required placeholder="مثال: 50 أو -20">
        </div>
        <div>
            <label>ملاحظة (اختياري)</label>
            <input type="text" name="note" placeholder="سبب التعديل">
        </div>
        <div class="full-width form-actions">
            <button type="submit" class="btn-primary">تطبيق</button>
            <a href="index.php?page=inventory" class="btn-secondary">إلغاء</a>
        </div>
    </form>
    </div>
    <?php
    return;
}

// قائمة المخزون
$items = [];
$invSearch = trim($_GET['q'] ?? '');
$invFilter = trim($_GET['filter'] ?? '');
$invExport = isset($_GET['export']) && $_GET['export'] === 'csv';
$invPage = max(1, (int)($_GET['p'] ?? 1));
$invPerPage = 30;
$invOffset = ($invPage - 1) * $invPerPage;

$tenantAnd = '';
try { $db->query('SELECT tenant_id FROM inventory_items LIMIT 1'); $tenantAnd = ' AND tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
$hasBatch = false;
$hasExpiry = false;
try { $db->query('SELECT batch_number FROM inventory_items LIMIT 1'); $hasBatch = true; } catch (Throwable $e) {}
try { $db->query('SELECT expiry_date FROM inventory_items LIMIT 1'); $hasExpiry = true; } catch (Throwable $e) {}

$sel = 'SELECT id, item_code, name, unit, current_quantity, min_quantity';
if ($hasBatch) $sel .= ', expiry_date, batch_number';
$sql = $sel . ' FROM inventory_items';
$where = $tenantAnd ? (' WHERE ' . substr($tenantAnd, 5)) : '';
$params = [];

if ($invSearch !== '') {
    $like = '%' . $invSearch . '%';
    $where .= ($where ? ' AND ' : ' WHERE ') . ($hasBatch ? '(name LIKE ? OR item_code LIKE ? OR batch_number LIKE ?)' : '(name LIKE ? OR item_code LIKE ?)');
    $params = $hasBatch ? [$like, $like, $like] : [$like, $like];
}
if ($invFilter === 'low') {
    $where .= ($where ? ' AND ' : ' WHERE ') . 'min_quantity > 0 AND current_quantity <= min_quantity';
} elseif ($invFilter === 'expired' && $hasExpiry) {
    $where .= ($where ? ' AND ' : ' WHERE ') . 'expiry_date IS NOT NULL AND expiry_date < CURDATE()';
}

$order = ' ORDER BY name ASC';

// إحصائيات
$invTotal = 0;
$invLowCount = 0;
$invExpiredCount = 0;
try {
    $stmt = $params ? $db->prepare('SELECT COUNT(*) FROM inventory_items' . $where) : $db->query('SELECT COUNT(*) FROM inventory_items' . $where);
    if ($params) $stmt->execute($params);
    $invTotal = (int)($stmt->fetchColumn() ?? 0);
    $lowWhere = ($tenantAnd ? (' WHERE ' . substr($tenantAnd, 5)) : ' WHERE 1=1') . ' AND min_quantity > 0 AND current_quantity <= min_quantity';
    $invLowCount = (int)($db->query('SELECT COUNT(*) FROM inventory_items' . $lowWhere)->fetchColumn() ?? 0);
    $expWhere = ($tenantAnd ? (' WHERE ' . substr($tenantAnd, 5)) : ' WHERE 1=1');
    try {
        $db->query('SELECT expiry_date FROM inventory_items LIMIT 1');
        $expWhere .= ' AND expiry_date IS NOT NULL AND expiry_date < CURDATE()';
        $invExpiredCount = (int)($db->query('SELECT COUNT(*) FROM inventory_items' . $expWhere)->fetchColumn() ?? 0);
    } catch (Throwable $e) {
        $invExpiredCount = 0;
    }
} catch (Throwable $e) {}

if ($invExport) {
    $stmt = ($params || $where) ? $db->prepare($sql . $where . $order) : $db->query($sql . $order);
    if ($params || $where) $stmt->execute($params);
    $items = $stmt->fetchAll();
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="inventory_' . date('Y-m-d') . '.csv"');
    echo "\xEF\xBB\xBF";
    echo "الكود,الاسم,الوحدة,الكمية,حد التنبيه,تاريخ الانتهاء,رقم الدفعة\n";
    foreach ($items as $r) {
        $line = [$r['item_code'], $r['name'], $r['unit'] ?? '', $r['current_quantity'], $r['min_quantity'], $r['expiry_date'] ?? '', $r['batch_number'] ?? ''];
        $escaped = [];
        foreach ($line as $v) {
            $v = (string)$v;
            if (strpbrk($v, ",\"\n\r") !== false) $v = '"' . str_replace('"', '""', $v) . '"';
            $escaped[] = $v;
        }
        echo implode(',', $escaped) . "\n";
    }
    exit;
}

$limit = ' LIMIT ' . (int)$invPerPage . ' OFFSET ' . (int)$invOffset;
$stmt = ($params || $where) ? $db->prepare($sql . $where . $order . $limit) : $db->query($sql . $order . $limit);
if ($params || $where) $stmt->execute($params);
$items = $stmt->fetchAll();
$cntSql = 'SELECT COUNT(*) FROM inventory_items' . $where;
$stmt = ($params || $where) ? $db->prepare($cntSql) : $db->query($cntSql);
if ($params || $where) $stmt->execute($params);
$invFilteredTotal = (int)($stmt->fetchColumn() ?? 0);
$invTotalPages = $invFilteredTotal > 0 ? (int)ceil($invFilteredTotal / $invPerPage) : 1;

$baseListUrl = 'index.php?page=inventory' . ($invSearch ? '&q=' . urlencode($invSearch) : '') . ($invFilter ? '&filter=' . urlencode($invFilter) : '');
?>
<div class="inventory-page">
    <header class="patients-header">
        <h1>المخزون</h1>
        <div class="patients-actions">
            <form method="get" class="patients-search-form">
                <input type="hidden" name="page" value="inventory">
                <input type="search" name="q" placeholder="بحث بالاسم أو الكود أو الدفعة..." value="<?php echo htmlspecialchars($invSearch, ENT_QUOTES, 'UTF-8'); ?>" class="patients-search-input">
                <select name="filter" onchange="this.form.submit()" style="padding:8px 12px;border-radius:var(--radius-sm);border:1px solid var(--border);">
                    <option value="" <?php echo $invFilter === '' ? 'selected' : ''; ?>>جميع المواد</option>
                    <option value="low" <?php echo $invFilter === 'low' ? 'selected' : ''; ?>>ناقص المخزون</option>
                    <?php if ($hasExpiry): ?><option value="expired" <?php echo $invFilter === 'expired' ? 'selected' : ''; ?>>منتهي الصلاحية</option><?php endif; ?>
                </select>
                <button type="submit" class="btn-secondary">بحث</button>
                <?php if ($invSearch || $invFilter): ?><a href="index.php?page=inventory" class="btn-secondary">مسح</a><?php endif; ?>
            </form>
            <?php if ($canManage): ?><a href="index.php?page=inventory&action=create" class="btn-primary">+ إضافة مادة</a><?php endif; ?>
            <a href="<?php echo $baseListUrl . '&export=csv'; ?>" class="btn-secondary">تصدير CSV</a>
        </div>
    </header>

    <section class="patients-stats inventory-stats">
        <div class="patients-stat-card">
            <span class="patients-stat-value"><?php echo number_format($invTotal); ?></span>
            <span class="patients-stat-label">إجمالي المواد</span>
        </div>
        <div class="patients-stat-card <?php echo $invLowCount > 0 ? 'stat-warning' : ''; ?>">
            <span class="patients-stat-value"><?php echo $invLowCount; ?></span>
            <span class="patients-stat-label">ناقص المخزون</span>
        </div>
        <div class="patients-stat-card <?php echo $invExpiredCount > 0 ? 'stat-danger' : ''; ?>">
            <span class="patients-stat-value"><?php echo $invExpiredCount; ?></span>
            <span class="patients-stat-label">منتهي الصلاحية</span>
        </div>
    </section>

    <div class="section-card">
        <div class="table-wrapper">
        <table class="table patients-table">
            <thead>
                <tr>
                    <th>الكود</th>
                    <th>الاسم</th>
                    <th>الوحدة</th>
                    <th>الكمية</th>
                    <th>حد التنبيه</th>
                    <th>تاريخ الانتهاء</th>
                    <th>رقم الدفعة</th>
                    <?php if ($canManage): ?><th style="width:200px;">إجراءات</th><?php endif; ?>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($items as $row): 
                $lowStock = (float)($row['current_quantity'] ?? 0) < (float)($row['min_quantity'] ?? 0) && (float)($row['min_quantity'] ?? 0) > 0;
                $expired = !empty($row['expiry_date']) && $row['expiry_date'] < date('Y-m-d');
            ?>
                <tr class="<?php echo $lowStock ? 'result-out-of-range' : ''; ?><?php echo $expired ? ' result-out-of-range' : ''; ?>">
                    <td><code class="patient-code"><?php echo htmlspecialchars($row['item_code'], ENT_QUOTES, 'UTF-8'); ?></code></td>
                    <td><strong><?php echo htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8'); ?></strong></td>
                    <td><?php echo htmlspecialchars($row['unit'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($row['current_quantity'], ENT_QUOTES, 'UTF-8'); ?><?php echo $lowStock ? ' ⚠️' : ''; ?></td>
                    <td><?php echo htmlspecialchars($row['min_quantity'] ?? '0', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo !empty($row['expiry_date']) ? htmlspecialchars($row['expiry_date'], ENT_QUOTES, 'UTF-8') . ($expired ? ' منتهي' : '') : '—'; ?></td>
                    <td><?php echo htmlspecialchars($row['batch_number'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></td>
                    <?php if ($canManage): ?>
                    <td class="patients-row-actions">
                        <a href="index.php?page=inventory&action=edit&id=<?php echo (int)$row['id']; ?>" class="btn-action btn-action--edit" title="تعديل">تعديل</a>
                        <a href="index.php?page=inventory&action=adjust&id=<?php echo (int)$row['id']; ?>" class="btn-action btn-action--order" title="ضبط الكمية">ضبط</a>
                    </td>
                    <?php endif; ?>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php if (empty($items)): ?>
        <p class="patients-empty">لا توجد نتائج. <?php if ($invSearch || $invFilter): ?><a href="index.php?page=inventory">عرض الكل</a><?php else: ?><a href="index.php?page=inventory&action=create">إضافة مادة جديدة</a><?php endif; ?></p>
        <?php endif; ?>
    </div>

    <?php if ($invTotalPages > 1): ?>
    <nav class="patients-pagination">
        <?php if ($invPage > 1): ?><a href="<?php echo $baseListUrl; ?>&p=<?php echo $invPage - 1; ?>" class="btn-secondary">← السابق</a><?php endif; ?>
        <span class="patients-pagination-info">صفحة <?php echo $invPage; ?> من <?php echo $invTotalPages; ?></span>
        <?php if ($invPage < $invTotalPages): ?><a href="<?php echo $baseListUrl; ?>&p=<?php echo $invPage + 1; ?>" class="btn-secondary">التالي →</a><?php endif; ?>
    </nav>
    <?php endif; ?>
</div>
