<?php
// ============================================
// API كامل للمدير - AUTO TESTER
// متوافق مع جدول inspection_requests
// ============================================

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: https://digitalsatcourses.com');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// إعدادات قاعدة البيانات
$host = "localhost";
$dbname = "digitals_autotester_db";
$username = "digitals_user";
$password_db = "bassam.bassam";

function sendResponse($success, $message = '', $data = null, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data,
        'timestamp' => date('Y-m-d H:i:s')
    ], JSON_UNESCAPED_UNICODE);
    exit();
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password_db);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $data = json_decode(file_get_contents('php://input'), true) ?? [];
    $action = $_GET['action'] ?? $data['action'] ?? null;
    
    // ============================================
    // 1. تسجيل الدخول
    // ============================================
    if ($action === 'login') {
        $email = $data['email'] ?? '';
        $password = $data['password'] ?? '';
        
        $stmt = $pdo->prepare("SELECT id, full_name, email, phone, password_hash, role, user_type, status FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        
        if (!$user || !password_verify($password, $user['password_hash'])) {
            sendResponse(false, 'بيانات الدخول غير صحيحة', null, 401);
        }
        
        $token = bin2hex(random_bytes(32));
        $expires = date('Y-m-d H:i:s', strtotime('+7 days'));
        
        // حذف الجلسات القديمة
        $stmt = $pdo->prepare("DELETE FROM admin_sessions WHERE user_id = ?");
        $stmt->execute([$user['id']]);
        
        // إنشاء جلسة جديدة
        $stmt = $pdo->prepare("INSERT INTO admin_sessions (user_id, token, expires_at) VALUES (?, ?, ?)");
        $stmt->execute([$user['id'], $token, $expires]);
        
        unset($user['password_hash']);
        
        sendResponse(true, 'تم تسجيل الدخول بنجاح', [
            'token' => $token,
            'user' => $user,
            'expires_at' => $expires
        ]);
    }
    
    // ============================================
    // 2. التحقق من التوكن
    // ============================================
    if ($action === 'verify_token') {
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        
        if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
            $token = trim($matches[1]);
            
            $stmt = $pdo->prepare("
                SELECT s.user_id, s.expires_at, u.id, u.full_name, u.email, u.phone, u.role, u.user_type, u.status
                FROM admin_sessions s
                JOIN users u ON s.user_id = u.id
                WHERE s.token = ? AND u.status = 'active'
            ");
            $stmt->execute([$token]);
            $session = $stmt->fetch();
            
            if ($session && strtotime($session['expires_at']) > time()) {
                // تجديد الجلسة
                $newExpires = date('Y-m-d H:i:s', strtotime('+7 days'));
                $stmt = $pdo->prepare("UPDATE admin_sessions SET expires_at = ? WHERE token = ?");
                $stmt->execute([$newExpires, $token]);
                
                sendResponse(true, 'توكن صالح', [
                    'user' => [
                        'id' => $session['id'],
                        'full_name' => $session['full_name'],
                        'email' => $session['email'],
                        'phone' => $session['phone'],
                        'role' => $session['role'],
                        'user_type' => $session['user_type']
                    ]
                ]);
            } else {
                sendResponse(false, 'توكن غير صالح', null, 401);
            }
        } else {
            sendResponse(false, 'لم يتم توفير توكن', null, 401);
        }
    }
    
    // ============================================
    // 3. إحصائيات لوحة التحكم (من inspection_requests)
    // ============================================
    if ($action === 'get_dashboard_stats') {
        // إحصائيات المستخدمين
        $stmt = $pdo->query("SELECT COUNT(*) as total FROM users");
        $totalUsers = $stmt->fetch()['total'];
        
        $stmt = $pdo->query("SELECT COUNT(*) as total FROM users WHERE role = 'inspector' OR user_type = 'inspector'");
        $totalInspectors = $stmt->fetch()['total'];
        
        $stmt = $pdo->query("SELECT COUNT(*) as total FROM users WHERE role = 'client' OR user_type = 'client'");
        $totalClients = $stmt->fetch()['total'];
        
        // ✅ إحصائيات الفحوصات من inspection_requests
        $stmt = $pdo->query("SELECT COUNT(*) as total FROM inspection_requests");
        $totalInspections = $stmt->fetch()['total'];
        
        $stmt = $pdo->query("SELECT COUNT(*) as total FROM inspection_requests WHERE status = 'pending'");
        $pendingInspections = $stmt->fetch()['total'];
        
        $stmt = $pdo->query("SELECT COUNT(*) as total FROM inspection_requests WHERE status = 'in_progress'");
        $inProgressInspections = $stmt->fetch()['total'];
        
        $stmt = $pdo->query("SELECT COUNT(*) as total FROM inspection_requests WHERE status = 'completed'");
        $completedInspections = $stmt->fetch()['total'];
        
        $stmt = $pdo->query("SELECT COUNT(*) as total FROM inspection_requests WHERE status = 'cancelled'");
        $cancelledInspections = $stmt->fetch()['total'];
        
        // إجمالي الإيرادات
        $stmt = $pdo->query("SELECT COALESCE(SUM(total_price), 0) as total FROM inspection_requests WHERE status = 'completed'");
        $totalRevenue = $stmt->fetch()['total'];
        
        // المراكز النشطة
        $stmt = $pdo->query("SELECT COUNT(*) as total FROM centers WHERE status = 'active'");
        $activeCenters = $stmt->fetch()['total'];
        
        // ✅ آخر الفحوصات
        $stmt = $pdo->query("
            SELECT 
                ir.id,
                ir.request_number,
                ir.client_name as customer_name,
                ir.client_phone as customer_phone,
                ir.car_brand as car_make,
                ir.car_model,
                ir.status,
                ir.created_at
            FROM inspection_requests ir
            ORDER BY ir.created_at DESC
            LIMIT 10
        ");
        $recentInspections = $stmt->fetchAll();
        
        sendResponse(true, 'تم جلب الإحصائيات', [
            'total_users' => (int)$totalUsers,
            'total_inspectors' => (int)$totalInspectors,
            'total_clients' => (int)$totalClients,
            'total_inspections' => (int)$totalInspections,
            'pending_inspections' => (int)$pendingInspections,
            'in_progress_inspections' => (int)$inProgressInspections,
            'completed_inspections' => (int)$completedInspections,
            'cancelled_inspections' => (int)$cancelledInspections,
            'total_revenue' => (float)$totalRevenue,
            'active_centers' => (int)$activeCenters,
            'inspector_stats' => [],
            'recent_inspections' => $recentInspections
        ]);
    }
    
    // ============================================
    // 4. جلب الفحوصات (من inspection_requests)
    // ============================================
    if ($action === 'get_inspections') {
        $status = $_GET['status'] ?? $data['status'] ?? null;
        
        $sql = "SELECT * FROM inspection_requests ORDER BY created_at DESC";
        $params = [];
        
        if ($status && $status !== 'all') {
            $sql = "SELECT * FROM inspection_requests WHERE status = ? ORDER BY created_at DESC";
            $params[] = $status;
        }
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $inspections = $stmt->fetchAll();
        
        sendResponse(true, 'تم جلب الفحوصات', $inspections);
    }
    
    // ============================================
    // 5. الطلبات المعلقة
    // ============================================
    if ($action === 'get_pending_inspections') {
        $stmt = $pdo->prepare("
            SELECT 
                ir.id,
                ir.request_number,
                ir.client_name as customer_name,
                ir.client_phone as customer_phone,
                ir.car_brand as car_make,
                ir.car_model,
                ir.status,
                ir.created_at,
                ir.address as area
            FROM inspection_requests ir
            WHERE ir.status = 'pending'
            ORDER BY ir.created_at ASC
        ");
        $stmt->execute();
        $inspections = $stmt->fetchAll();
        
        sendResponse(true, 'تم جلب الطلبات المعلقة', $inspections);
    }
    
    // ============================================
    // 6. جلب المستخدمين
    // ============================================
    if ($action === 'get_users') {
        $stmt = $pdo->query("SELECT id, full_name, email, phone, role, user_type, status, created_at FROM users ORDER BY created_at DESC");
        $users = $stmt->fetchAll();
        sendResponse(true, 'تم جلب المستخدمين', $users);
    }
    
    // ============================================
    // 7. جلب الفاحصين
    // ============================================
    if ($action === 'get_inspectors') {
        $stmt = $pdo->query("SELECT id, full_name, email, phone, area, assigned_region, rating, status FROM users WHERE role = 'inspector' OR user_type = 'inspector'");
        $inspectors = $stmt->fetchAll();
        sendResponse(true, 'تم جلب الفاحصين', $inspectors);
    }
    
    // ============================================
    // 8. جلب العملاء
    // ============================================
    if ($action === 'get_clients') {
        $stmt = $pdo->query("SELECT id, full_name, email, phone, status, created_at FROM users WHERE role = 'client' OR user_type = 'client'");
        $clients = $stmt->fetchAll();
        sendResponse(true, 'تم جلب العملاء', $clients);
    }
    
  // ============================================
// جلب جميع المراكز
// ============================================
if ($action === 'get_centers') {
    try {
        // التحقق من وجود جدول centers
        $stmt = $pdo->query("SHOW TABLES LIKE 'centers'");
        if ($stmt->rowCount() == 0) {
            sendResponse(true, 'لا يوجد جدول centers بعد', []);
        }
        
        // جلب جميع المراكز
        $stmt = $pdo->query("
            SELECT 
                id, 
                name, 
                name_ar, 
                location, 
                region, 
                region_ar, 
                address,
                latitude, 
                longitude, 
                working_hours_from, 
                working_hours_to,
                manager_name, 
                manager_phone, 
                status, 
                updated_at
            FROM centers 
            ORDER BY id ASC
        ");
        
        $centers = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // تحويل NULL إلى سلاسل فارغة للعرض
        foreach ($centers as &$center) {
            foreach ($center as $key => $value) {
                if ($value === null) {
                    $center[$key] = '';
                }
            }
        }
        
        sendResponse(true, 'تم جلب المراكز بنجاح', $centers);
        
    } catch (PDOException $e) {
        sendResponse(false, 'خطأ في قاعدة البيانات: ' . $e->getMessage(), null, 500);
    }
}
    
   // ============================================
// إضافة مركز جديد
// ============================================
if ($action === 'add_center') {
    $name = $data['name'] ?? null;
    $location = $data['location'] ?? null;
    $region = $data['region'] ?? null;
    $address = $data['address'] ?? null;
    
    if (!$name || !$location) {
        sendResponse(false, 'اسم المركز والموقع مطلوبان', null, 400);
    }
    
    $stmt = $pdo->prepare("
        INSERT INTO centers (
            name, name_ar, location, region, region_ar, address, 
            latitude, longitude, working_hours_from, working_hours_to,
            manager_name, manager_phone, status, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW())
    ");
    
    $nameAr = $data['name_ar'] ?? $name;
    $regionAr = $data['region_ar'] ?? $region;
    $latitude = $data['latitude'] ?? null;
    $longitude = $data['longitude'] ?? null;
    $workingHoursFrom = $data['working_hours_from'] ?? '09:00:00';
    $workingHoursTo = $data['working_hours_to'] ?? '17:00:00';
    $managerName = $data['manager_name'] ?? null;
    $managerPhone = $data['manager_phone'] ?? null;
    
    $stmt->execute([
        $name, $nameAr, $location, $region, $regionAr, $address,
        $latitude, $longitude, $workingHoursFrom, $workingHoursTo,
        $managerName, $managerPhone
    ]);
    
    sendResponse(true, 'تم إضافة المركز بنجاح', ['id' => $pdo->lastInsertId()]);
}

// ============================================
// تحديث مركز
// ============================================
if ($action === 'update_center') {
    $centerId = $data['id'] ?? null;
    
    if (!$centerId) {
        sendResponse(false, 'معرف المركز مطلوب', null, 400);
    }
    
    $updates = [];
    $params = [];
    
    $allowedFields = ['name', 'name_ar', 'location', 'region', 'region_ar', 'address', 
                      'latitude', 'longitude', 'working_hours_from', 'working_hours_to',
                      'manager_name', 'manager_phone', 'status'];
    
    foreach ($allowedFields as $field) {
        if (isset($data[$field])) {
            $updates[] = "$field = ?";
            $params[] = $data[$field];
        }
    }
    
    if (empty($updates)) {
        sendResponse(false, 'لا توجد بيانات للتحديث', null, 400);
    }
    
    $params[] = $centerId;
    $sql = "UPDATE centers SET " . implode(', ', $updates) . ", updated_at = NOW() WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    
    sendResponse(true, 'تم تحديث المركز بنجاح');
}

// ============================================
// حذف مركز
// ============================================
if ($action === 'delete_center') {
    $centerId = $_GET['id'] ?? $data['id'] ?? null;
    
    if (!$centerId) {
        sendResponse(false, 'معرف المركز مطلوب', null, 400);
    }
    
    $stmt = $pdo->prepare("DELETE FROM centers WHERE id = ?");
    $stmt->execute([$centerId]);
    
    sendResponse(true, 'تم حذف المركز بنجاح');
}

// ============================================
// جلب مركز واحد
// ============================================
if ($action === 'get_center') {
    $centerId = $_GET['id'] ?? $data['id'] ?? null;
    
    if (!$centerId) {
        sendResponse(false, 'معرف المركز مطلوب', null, 400);
    }
    
    $stmt = $pdo->prepare("SELECT * FROM centers WHERE id = ?");
    $stmt->execute([$centerId]);
    $center = $stmt->fetch();
    
    sendResponse(true, 'تم جلب بيانات المركز', $center);
}
    
    // ============================================
    // 11. تحديث حالة الفحص
    // ============================================
    if ($action === 'update_inspection_status') {
        $inspectionId = $data['id'] ?? null;
        $newStatus = $data['status'] ?? null;
        
        if (!$inspectionId || !$newStatus) {
            sendResponse(false, 'معرف الفحص والحالة مطلوبان', null, 400);
        }
        
        $stmt = $pdo->prepare("UPDATE inspection_requests SET status = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$newStatus, $inspectionId]);
        
        sendResponse(true, 'تم تحديث حالة الفحص بنجاح');
    }
    
    // ============================================
    // 12. تحديث مستخدم
    // ============================================
    if ($action === 'update_user') {
        $userId = $data['id'] ?? null;
        if (!$userId) {
            sendResponse(false, 'معرف المستخدم مطلوب', null, 400);
        }
        
        $updates = [];
        $params = [];
        
        if (isset($data['full_name'])) {
            $updates[] = "full_name = ?";
            $params[] = $data['full_name'];
        }
        if (isset($data['email'])) {
            $updates[] = "email = ?";
            $params[] = $data['email'];
        }
        if (isset($data['phone'])) {
            $updates[] = "phone = ?";
            $params[] = $data['phone'];
        }
        
        if (empty($updates)) {
            sendResponse(false, 'لا توجد بيانات للتحديث', null, 400);
        }
        
        $params[] = $userId;
        $sql = "UPDATE users SET " . implode(', ', $updates) . " WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        sendResponse(true, 'تم تحديث المستخدم بنجاح');
    }
   
    // ============================================
    // جلب سجل النشاطات
    // ============================================
    if ($action === 'get_activity_log') {
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        
        if (!preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
            sendResponse(false, 'لم يتم توفير توكن', null, 401);
        }
        
        $token = trim($matches[1]);
        
        $stmt = $pdo->prepare("SELECT user_id FROM admin_sessions WHERE token = ?");
        $stmt->execute([$token]);
        $session = $stmt->fetch();
        
        if (!$session) {
            sendResponse(false, 'جلسة غير صالحة', null, 401);
        }
        
        $limit = (int)($_GET['limit'] ?? 200);
        
        try {
            // التحقق من وجود جدول user_activity_log
            $stmt = $pdo->query("SHOW TABLES LIKE 'user_activity_log'");
            if ($stmt->rowCount() == 0) {
                // إنشاء الجدول إذا لم يكن موجوداً
                $pdo->exec("
                    CREATE TABLE IF NOT EXISTS user_activity_log (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        user_id INT NOT NULL,
                        action VARCHAR(100) NOT NULL,
                        details TEXT,
                        ip_address VARCHAR(45),
                        user_agent TEXT,
                        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        INDEX idx_user_id (user_id),
                        INDEX idx_action (action),
                        INDEX idx_created_at (created_at)
                    )
                ");
                sendResponse(true, 'سجل النشاطات فارغ (تم إنشاء الجدول)', []);
            }
            
            $stmt = $pdo->prepare("
                SELECT al.*, u.full_name as user_name
                FROM user_activity_log al
                LEFT JOIN users u ON al.user_id = u.id
                ORDER BY al.created_at DESC
                LIMIT ?
            ");
            $stmt->execute([$limit]);
            $activities = $stmt->fetchAll();
            
            sendResponse(true, 'تم جلب سجل النشاطات', $activities);
            
        } catch (Exception $e) {
            sendResponse(true, 'لا توجد نشاطات بعد', []);
        }
    }
 
    // ============================================
    // 13. تسجيل الخروج
    // ============================================
    if ($action === 'logout') {
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        
        if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
            $stmt = $pdo->prepare("DELETE FROM admin_sessions WHERE token = ?");
            $stmt->execute([$matches[1]]);
        }
        sendResponse(true, 'تم تسجيل الخروج بنجاح');
    }
    
    // ============================================
    // الإجراء غير الموجود
    // ============================================
    sendResponse(false, 'الإجراء المطلوب غير موجود', [
        'available_actions' => [
            'login', 'verify_token', 'logout',
            'get_dashboard_stats', 'get_inspections', 'get_pending_inspections',
            'get_users', 'get_inspectors', 'get_clients', 'get_centers',
            'add_inspection', 'update_inspection_status', 'update_user'
        ]
    ], 400);
    
} catch (PDOException $e) {
    sendResponse(false, 'خطأ في قاعدة البيانات: ' . $e->getMessage(), null, 500);
} catch (Exception $e) {
    sendResponse(false, 'خطأ في الخادم: ' . $e->getMessage(), null, 500);
}
?>