<?php
/**
 * Prince VIP System - Clients AJAX Handler
 */
require_once __DIR__ . '/../config/database.php';
if (!isLoggedIn()) { echo json_encode(['success' => false, 'message' => 'غير مصرح']); exit; }

$db = getDB();
$action = $_POST['action'] ?? '';

switch ($action) {
    case 'create':
        $name = clean($_POST['full_name'] ?? '');
        $idNum = clean($_POST['id_number'] ?? '');
        $phone = clean($_POST['phone'] ?? '');
        $email = clean($_POST['email'] ?? '');
        $address = clean($_POST['address'] ?? '');
        
        if (empty($name) || empty($idNum) || empty($phone)) {
            echo json_encode(['success' => false, 'message' => 'يرجى إكمال البيانات المطلوبة']);
            exit;
        }
        
        $check = $db->prepare("SELECT id FROM clients WHERE id_number = ?");
        $check->execute([$idNum]);
        if ($check->fetch()) {
            echo json_encode(['success' => false, 'message' => 'رقم الهوية مسجل مسبقاً']);
            exit;
        }
        
        $db->prepare("INSERT INTO clients (full_name, id_number, phone, email, address, created_by) VALUES (?,?,?,?,?,?)")
           ->execute([$name, $idNum, $phone, $email, $address, $_SESSION['user_id']]);
        
        echo json_encode(['success' => true, 'message' => 'تم إضافة العميل بنجاح', 'id' => $db->lastInsertId()]);
        break;
    
    case 'update':
        $clientId = (int)($_POST['client_id'] ?? 0);
        $db->prepare("UPDATE clients SET full_name=?, id_number=?, phone=?, email=?, address=? WHERE id=?")
           ->execute([clean($_POST['full_name']), clean($_POST['id_number']), clean($_POST['phone']), clean($_POST['email'] ?? ''), clean($_POST['address'] ?? ''), $clientId]);
        echo json_encode(['success' => true, 'message' => 'تم تحديث بيانات العميل']);
        break;
    
    case 'list':
        $page = max(1, (int)($_POST['page'] ?? 1));
        $perPage = 15;
        $offset = ($page - 1) * $perPage;
        $search = clean($_POST['search'] ?? '');
        
        $where = '';
        $params = [];
        
        if (!isAdmin()) {
            $where = "WHERE cl.created_by = ?";
            $params[] = $_SESSION['user_id'];
        }
        
        if ($search) {
            $where .= ($where ? ' AND' : 'WHERE') . " (cl.full_name LIKE ? OR cl.id_number LIKE ? OR cl.phone LIKE ?)";
            $params[] = "%$search%";
            $params[] = "%$search%";
            $params[] = "%$search%";
        }
        
        $sql = "SELECT cl.*, (SELECT COUNT(*) FROM contracts WHERE client_id = cl.id) as contracts_count 
                FROM clients cl $where ORDER BY cl.created_at DESC LIMIT $perPage OFFSET $offset";
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        
        echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
        break;
    
    case 'search':
        $q = clean($_POST['q'] ?? '');
        $params = ["%$q%", "%$q%"];
        $whereExtra = '';
        if (!isAdmin()) {
            $whereExtra = "AND created_by = ?";
            $params[] = $_SESSION['user_id'];
        }
        $stmt = $db->prepare("SELECT id, full_name, id_number, phone FROM clients WHERE (full_name LIKE ? OR id_number LIKE ?) $whereExtra ORDER BY full_name LIMIT 20");
        $stmt->execute($params);
        echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
        break;
    
    default:
        echo json_encode(['success' => false, 'message' => 'إجراء غير معروف']);
}
