<?php
/**
 * API: جلب قائمة الشركات والمعارض
 * GET /api/admin/endpoints/get_companies.php
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');

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

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

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // جلب الشركات من جدول companies
    $query = "SELECT 
                comp.id,
                comp.request_number,
                comp.user_id,
                comp.company_name,
                comp.commercial_record,
                comp.tax_number,
                comp.business_type,
                comp.contact_name,
                comp.contact_phone,
                comp.contact_email,
                comp.governorate,
                comp.city,
                comp.address,
                comp.photo_path,
                comp.documents,
                comp.status,
                comp.created_at,
                u.username
              FROM companies comp
              LEFT JOIN users u ON comp.user_id = u.id
              ORDER BY 
                CASE WHEN comp.status = 'pending' THEN 1 ELSE 2 END,
                comp.created_at DESC";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $companies = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $companies,
        'total' => count($companies),
        'timestamp' => date('Y-m-d H:i:s')
    ], JSON_UNESCAPED_UNICODE);
    
} catch(PDOException $e) {
    error_log("Database error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>