<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Set content type to JSON
header('Content-Type: application/json');

// Check if user is logged in as IT
if (!is_logged_in() || !is_user_type('it')) {
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access'
    ]);
    exit();
}

try {
    // Get filter parameters
    $buyer_id = isset($_GET['buyer_id']) ? intval($_GET['buyer_id']) : 0;
    $code_color = isset($_GET['code_color']) ? trim($_GET['code_color']) : '';
    
    // Build query
    $query = "SELECT mcp.*, b.nama_buyer as buyer_name, b.kode_buyer, c.nama_collection,
                     COUNT(csi.id) as total_stock_items,
                     COUNT(CASE WHEN csi.status = 'Tersedia' THEN 1 END) as available_items,
                     COUNT(CASE WHEN csi.status = 'Dipinjam' THEN 1 END) as borrowed_items,
                     COUNT(CASE WHEN csi.status = 'Rusak' THEN 1 END) as damaged_items,
                     COUNT(CASE WHEN csi.status = 'Expired' THEN 1 END) as expired_items
              FROM master_color_panel mcp 
              JOIN buyers b ON mcp.buyer_id = b.id 
              JOIN collections c ON mcp.collection_id = c.id
              LEFT JOIN color_stock_items csi ON mcp.id = csi.color_id
              WHERE 1=1";
    
    $params = [];
    $types = "";
    
    // Add filters
    if ($buyer_id > 0) {
        $query .= " AND mcp.buyer_id = ?";
        $params[] = $buyer_id;
        $types .= "i";
    }
    
    if (!empty($code_color)) {
        $query .= " AND mcp.code_color LIKE ?";
        $params[] = "%" . $code_color . "%";
        $types .= "s";
    }
    
    $query .= " GROUP BY mcp.id ORDER BY b.nama_buyer, mcp.code_color";
    
    // Prepare and execute statement
    $stmt = $conn->prepare($query);
    
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    
    $stmt->execute();
    $result = $stmt->get_result();
    
    $color_panels = [];
    while ($row = $result->fetch_assoc()) {
        // Get component count for this color panel
        $component_query = "SELECT COUNT(*) as component_count FROM color_panel_components WHERE color_id = ?";
        $comp_stmt = $conn->prepare($component_query);
        $comp_stmt->bind_param("i", $row['id']);
        $comp_stmt->execute();
        $comp_result = $comp_stmt->get_result();
        $component_count = $comp_result->fetch_assoc()['component_count'];
        $comp_stmt->close();
        
        // Add component count to row data
        $row['component_count'] = $component_count;
        
        // Format data for display
        $row['total_stock_items'] = intval($row['total_stock_items']);
        $row['available_items'] = intval($row['available_items']);
        $row['borrowed_items'] = intval($row['borrowed_items']);
        $row['damaged_items'] = intval($row['damaged_items']);
        $row['expired_items'] = intval($row['expired_items']);
        
        // Escape HTML special characters for safe display
        $row['code_color'] = htmlspecialchars($row['code_color']);
        $row['deskripsi'] = htmlspecialchars($row['deskripsi'] ?: '');
        $row['buyer_name'] = htmlspecialchars($row['buyer_name']);
        $row['keterangan_warna'] = htmlspecialchars($row['keterangan_warna'] ?: '');
        
        $color_panels[] = $row;
    }
    
    $stmt->close();
    
    // Log the access
    $it_id = $_SESSION['user_id'];
    $filter_details = [];
    if ($buyer_id > 0) $filter_details[] = "buyer_id: $buyer_id";
    if (!empty($code_color)) $filter_details[] = "code_color: $code_color";
    $filter_str = !empty($filter_details) ? implode(', ', $filter_details) : 'no filters';
    
    create_audit_log($conn, 'Color Panel Search', $it_id, 'it', "Searched color panels with filters: $filter_str. Found " . count($color_panels) . " results.");
    
    // Return success response
    echo json_encode([
        'success' => true,
        'data' => $color_panels,
        'total' => count($color_panels),
        'message' => 'Data loaded successfully'
    ]);

} catch (Exception $e) {
    // Log error
    error_log("Error in ajax_get_color_panels.php: " . $e->getMessage());
    
    // Return error response
    echo json_encode([
        'success' => false,
        'message' => 'Terjadi kesalahan saat memuat data: ' . $e->getMessage()
    ]);
}
?>