<?php
require_once 'auth.php';
requireLogin();

$success = '';
$error = '';

if (isset($_GET['imported'])) {
    $imp = (int)$_GET['imported'];
    $skip = (int)($_GET['skipped'] ?? 0);
    $success = "تم استيراد $imp مهندس بنجاح" . ($skip > 0 ? " وتخطي $skip (موجود مسبقاً)" : "");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_FILES['import_file']['name']) && isset($_POST['action']) && $_POST['action'] === 'import') {
    if (function_exists('require_csrf')) require_csrf();
    if (!canEdit()) { header('Location: engineers.php'); exit; }
    $ext = strtolower(pathinfo($_FILES['import_file']['name'], PATHINFO_EXTENSION));
    $allowed = ['xlsx', 'xls', 'csv'];
    if (!in_array($ext, $allowed)) {
        $error = 'صيغة الملف غير مدعومة. استخدم xlsx أو xls أو csv';
    } elseif ($_FILES['import_file']['error'] !== UPLOAD_ERR_OK) {
        $error = 'فشل رفع الملف';
    } else {
        $tmp = $_FILES['import_file']['tmp_name'];
        $existing = [];
        $r = $conn->query("SELECT name FROM engineers");
        while ($row = $r->fetch_assoc()) $existing[trim($row['name'])] = 1;
        $imported = 0;
        $skipped = 0;
        if ($ext === 'csv') {
            $handle = fopen($tmp, 'r');
            if ($handle) {
                $bom = fread($handle, 3);
                if ($bom !== chr(0xEF).chr(0xBB).chr(0xBF)) rewind($handle);
                $header = fgetcsv($handle);
                $nameCol = 0;
                if ($header) foreach ($header as $i => $h) {
                    if (stripos((string)$h, 'اسم') !== false || stripos((string)$h, 'مهندس') !== false || $h === 'name') $nameCol = $i;
                }
                while (($row = fgetcsv($handle)) !== false) {
                    $name = trim($row[$nameCol] ?? $row[0] ?? '');
                    if (empty($name)) continue;
                    if (isset($existing[$name])) { $skipped++; continue; }
                    $stmt = $conn->prepare("INSERT INTO engineers (name) VALUES (?)");
                    $stmt->bind_param("s", $name);
                    if ($stmt->execute()) {
                        $imported++;
                        $existing[$name] = 1;
                        if (function_exists('logActivity')) logActivity('add', 'engineers', $conn->insert_id, $name . ' (استيراد)');
                    } else $skipped++;
                }
                fclose($handle);
            }
        } else {
            if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
                $error = 'مكتبة Excel غير متوفرة. استخدم ملف CSV للاستيراد.';
            } else {
                require_once __DIR__ . '/vendor/autoload.php';
                $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($ext === 'xlsx' ? 'Xlsx' : 'Xls');
                $spreadsheet = $reader->load($tmp);
                $sheet = $spreadsheet->getActiveSheet();
                $rows = $sheet->toArray();
                $nameCol = 0;
                if (!empty($rows[0])) {
                    foreach ($rows[0] as $i => $h) {
                        $h = is_string($h) ? $h : '';
                        if (stripos($h, 'اسم') !== false || stripos($h, 'مهندس') !== false || $h === 'name') $nameCol = $i;
                    }
                }
                for ($i = 1; $i < count($rows); $i++) {
                    $row = $rows[$i] ?? [];
                    $name = trim($row[$nameCol] ?? $row[0] ?? '');
                    if (empty($name)) continue;
                    if (isset($existing[$name])) { $skipped++; continue; }
                    $stmt = $conn->prepare("INSERT INTO engineers (name) VALUES (?)");
                    $stmt->bind_param("s", $name);
                    if ($stmt->execute()) {
                        $imported++;
                        $existing[$name] = 1;
                        if (function_exists('logActivity')) logActivity('add', 'engineers', $conn->insert_id, $name . ' (استيراد)');
                    } else $skipped++;
                }
            }
        }
        if (empty($error)) {
            header('Location: engineers.php?imported=' . $imported . '&skipped=' . $skipped);
            exit;
        }
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (function_exists('require_csrf')) require_csrf();
    if (!canEdit()) { header('Location: engineers.php'); exit; }
    $name = trim($_POST['name'] ?? '');
    if (empty($name)) {
        $error = 'يرجى إدخال اسم المهندس';
    } else {
        $stmt = $conn->prepare("INSERT INTO engineers (name) VALUES (?)");
        $stmt->bind_param("s", $name);
        if ($stmt->execute()) {
            if (function_exists('logActivity')) logActivity('add', 'engineers', $conn->insert_id, $name);
            $success = 'تم إضافة المهندس بنجاح';
            $_POST = [];
        } else {
            $error = 'الاسم موجود مسبقاً أو حدث خطأ';
        }
    }
}

$search = trim($_GET['q'] ?? '');
$where = $search ? " WHERE name LIKE '%" . $conn->real_escape_string($search) . "%'" : '';
$engineers = $conn->query("SELECT e.*, (SELECT COUNT(*) FROM devices d WHERE d.engineer_id = e.id) as device_count FROM engineers e $where ORDER BY e.name");

$stats_total = $conn->query("SELECT COUNT(*) c FROM engineers")->fetch_assoc()['c'];
$stats_with_devices = $conn->query("SELECT COUNT(DISTINCT engineer_id) c FROM devices")->fetch_assoc()['c'];
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <?php include 'includes/favicon.php'; ?>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>المهندسين - نظام صيانة</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <link href="assets/css/dashboard.css" rel="stylesheet">
    <style>
        .eng-stat-card { border-radius: 16px; transition: transform 0.2s; }
        .eng-stat-card:hover { transform: translateY(-2px); }
    </style>
</head>
<body class="dashboard-body">
    <?php include 'includes/header.php'; ?>
    
    <div class="main-content">
        <div class="container-fluid py-4 px-4">
            <nav aria-label="breadcrumb" class="mb-3">
                <ol class="breadcrumb mb-0">
                    <li class="breadcrumb-item"><a href="dashboard.php">الرئيسية</a></li>
                    <li class="breadcrumb-item"><a href="dashboard.php">الإعدادات</a></li>
                    <li class="breadcrumb-item active">المهندسين</li>
                </ol>
            </nav>

            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
                <h2 class="page-title mb-0"><i class="bi bi-person-badge me-2"></i>إضافة المهندسين</h2>
                <div class="d-flex gap-2">
                    <?php if (canExport()): ?><a href="export.php?type=engineers" class="btn btn-success btn-sm"><i class="bi bi-file-excel me-1"></i> تصدير Excel</a><?php endif; ?>
                    <?php if (canEdit()): ?><button type="button" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#importModal"><i class="bi bi-upload me-1"></i> استيراد Excel</button><?php endif; ?>
                </div>
            </div>

            <!-- بطاقات الإحصائيات -->
            <div class="row g-3 mb-4">
                <div class="col-6 col-md-4">
                    <div class="card eng-stat-card h-100" style="background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%); border: 1px solid #93c5fd;">
                        <div class="card-body d-flex align-items-center gap-3 py-3">
                            <div class="rounded-circle bg-primary bg-opacity-25 p-3">
                                <i class="bi bi-person-badge text-primary fs-5"></i>
                            </div>
                            <div>
                                <h3 class="mb-0 fw-700"><?= $stats_total ?></h3>
                                <small class="text-primary fw-600">إجمالي المهندسين</small>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-6 col-md-4">
                    <div class="card eng-stat-card h-100" style="background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%); border: 1px solid #86efac;">
                        <div class="card-body d-flex align-items-center gap-3 py-3">
                            <div class="rounded-circle bg-success bg-opacity-25 p-3">
                                <i class="bi bi-cpu text-success fs-5"></i>
                            </div>
                            <div>
                                <h3 class="mb-0 fw-700"><?= $stats_with_devices ?></h3>
                                <small class="text-success fw-600">مهندسين لديهم أجهزة</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row g-4">
                <?php if (canEdit()): ?>
                <div class="col-lg-4">
                    <div class="card">
                        <div class="card-header bg-primary text-white">
                            <h5 class="mb-0"><i class="bi bi-plus-circle me-2"></i>إضافة مهندس جديد</h5>
                        </div>
                        <div class="card-body">
                            <?php if ($success): ?>
                            <div class="alert alert-success d-flex align-items-center">
                                <i class="bi bi-check-circle me-2"></i><?= $success ?>
                            </div>
                            <?php endif; ?>
                            <?php if ($error): ?>
                            <div class="alert alert-danger d-flex align-items-center">
                                <i class="bi bi-exclamation-circle me-2"></i><?= $error ?>
                            </div>
                            <?php endif; ?>
                            <form method="POST">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <div class="mb-3">
                                    <label class="form-label fw-600">اسم المهندس</label>
                                    <input type="text" name="name" class="form-control" required 
                                        placeholder="أدخل اسم المهندس" value="<?= htmlspecialchars($_POST['name'] ?? '') ?>">
                                </div>
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="bi bi-plus-lg me-1"></i> إضافة
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                <div class="col-lg-<?= canEdit() ? 8 : 12 ?>">
                    <div class="card">
                        <div class="card-header bg-white d-flex justify-content-between align-items-center flex-wrap gap-2 py-3">
                            <h5 class="mb-0 fw-600"><i class="bi bi-list me-2"></i>قائمة المهندسين</h5>
                            <form method="GET" class="d-flex gap-2">
                                <input type="text" name="q" class="form-control form-control-sm" placeholder="بحث بالاسم..." value="<?= htmlspecialchars($search) ?>" style="max-width: 220px;">
                                <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-search"></i></button>
                                <?php if ($search): ?><a href="engineers.php" class="btn btn-outline-secondary btn-sm">إلغاء</a><?php endif; ?>
                            </form>
                        </div>
                        <div class="card-body p-0 overflow-auto" style="max-height: 50vh;">
                            <table class="table table-hover mb-0">
                                <thead class="table-light">
                                    <tr><th>#</th><th>الاسم</th><th>عدد الأجهزة</th><?php if (canEdit() || canDelete()): ?><th>إجراءات</th><?php endif; ?></tr>
                                </thead>
                                <tbody>
                                <?php while ($e = $engineers->fetch_assoc()): 
                                    $devCount = (int)($e['device_count'] ?? 0);
                                    $canDelete = $devCount === 0;
                                ?>
                                <tr class="align-middle">
                                    <td><?= $e['id'] ?></td>
                                    <td class="fw-500"><?= htmlspecialchars($e['name']) ?></td>
                                    <td>
                                        <?php if ($devCount > 0): ?>
                                        <a href="devices_list.php?engineer_id=<?= $e['id'] ?>" class="badge bg-primary text-decoration-none"><?= $devCount ?></a>
                                        <?php else: ?>
                                        <span class="text-muted">0</span>
                                        <?php endif; ?>
                                    </td>
                                    <?php if (canEdit() || canDelete()): ?><td>
                                        <?php if (canEdit()): ?><button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editModal" 
                                            data-id="<?= $e['id'] ?>" data-name="<?= htmlspecialchars($e['name']) ?>">
                                            <i class="bi bi-pencil"></i>
                                        </button><?php endif; ?>
                                        <?php if ($canDelete && canDelete()): ?>
                                        <button type="button" class="btn btn-sm btn-outline-danger btn-delete" data-id="<?= $e['id'] ?>" title="حذف">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                        <?php elseif (!$canDelete): ?>
                                        <span class="badge bg-secondary" title="مرتبط بأجهزة">—</span>
                                        <?php endif; ?>
                                    </td><?php endif; ?>
                                </tr>
                                <?php endwhile; ?>
                                <?php if ($engineers->num_rows === 0): ?>
                                <tr>
                                    <td colspan="<?= (canEdit() || canDelete()) ? 4 : 3 ?>" class="text-center text-muted py-5">
                                        <i class="bi bi-person-badge fs-1 d-block mb-2"></i>
                                        <?= $search ? 'لا توجد نتائج' : 'لا يوجد مهندسين مسجلين' ?>
                                    </td>
                                </tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- نافذة الاستيراد -->
    <?php if (canEdit()): ?>
    <div class="modal fade" id="importModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-upload me-2"></i>استيراد المهندسين من Excel</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" enctype="multipart/form-data">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="import">
                    <div class="modal-body">
                        <p class="text-muted small">الصيغ المدعومة: xlsx, xls, csv. العمود الأول أو العمود الذي يحتوي "اسم" أو "مهندس" سيُستخدم. المهندسون المكررون يُتخطَوْن.</p>
                        <div class="mb-3">
                            <label class="form-label">اختر الملف</label>
                            <input type="file" name="import_file" class="form-control" accept=".xlsx,.xls,.csv" required>
                        </div>
                        <p class="small"><a href="export.php?type=engineers" class="text-primary">حمّل ملف نموذج</a> من التصدير ثم أضف المهندسين الجدد فيه.</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                        <button type="submit" class="btn btn-success"><i class="bi bi-upload me-1"></i>استيراد</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- نافذة التعديل -->
    <div class="modal fade" id="editModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-pencil me-2"></i>تعديل المهندس</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="edit_id">
                    <div class="mb-3">
                        <label class="form-label">الاسم</label>
                        <input type="text" id="edit_name" class="form-control" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="button" class="btn btn-primary" id="saveEdit"><i class="bi bi-check me-1"></i>حفظ</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    document.getElementById('editModal')?.addEventListener('show.bs.modal', function(e) {
        const btn = e.relatedTarget;
        if (btn?.dataset?.id) {
            document.getElementById('edit_id').value = btn.dataset.id;
            document.getElementById('edit_name').value = btn.dataset.name || '';
        }
    });
    document.getElementById('saveEdit')?.addEventListener('click', function() {
        const fd = new FormData();
        fd.append('action', 'update');
        fd.append('id', document.getElementById('edit_id').value);
        fd.append('name', document.getElementById('edit_name').value);
        if (window.csrfToken) fd.append('csrf_token', window.csrfToken);
        fetch('api/engineers.php', { method: 'POST', body: fd })
            .then(r => r.json())
            .then(d => { 
                if (d.success) location.reload(); 
                else alert(d.message || 'فشل التحديث'); 
            });
    });
    document.querySelectorAll('.btn-delete').forEach(btn => {
        btn.addEventListener('click', function() {
            if (confirm('حذف هذا المهندس؟')) {
                const u = 'api/engineers.php?action=delete&id=' + this.dataset.id + (window.csrfToken ? '&csrf_token=' + window.csrfToken : '');
                fetch(u)
                    .then(r => r.json())
                    .then(d => { 
                        if (d.success) location.reload(); 
                        else alert(d.message || 'فشل الحذف'); 
                    });
            }
        });
    });
    </script>
    <?php include 'includes/footer.php'; ?>
</body>
</html>
