<?php
// Start session
session_start();

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

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

// Check if user is logged in and is IT user
if (!isset($_SESSION['user_type']) || $_SESSION['user_type'] !== 'it') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Get buyer ID from request
$buyer_id = isset($_GET['buyer_id']) ? (int)$_GET['buyer_id'] : 0;

try {
    // Get buyer name if specific buyer selected
    $buyer_name = null;
    if ($buyer_id > 0) {
        $buyer_stmt = $conn->prepare("SELECT nama_buyer FROM buyers_semarang WHERE id = ?");
        $buyer_stmt->bind_param("i", $buyer_id);
        $buyer_stmt->execute();
        $buyer_result = $buyer_stmt->get_result();
        if ($buyer_row = $buyer_result->fetch_assoc()) {
            $buyer_name = $buyer_row['nama_buyer'];
        }
        $buyer_stmt->close();
    }
    
    // Count total items
    $count_query = "
        SELECT COUNT(*) as total
        FROM color_stock_items_semarang csi
        JOIN master_color_panel_semarang mcp ON csi.color_id = mcp.id
    ";
    
    if ($buyer_id > 0) {
        $count_query .= " WHERE mcp.buyer_id = ?";
    }
    
    $count_stmt = $conn->prepare($count_query);
    if ($buyer_id > 0) {
        $count_stmt->bind_param("i", $buyer_id);
    }
    $count_stmt->execute();
    $count_result = $count_stmt->get_result();
    $total_items = $count_result->fetch_assoc()['total'];
    $count_stmt->close();
    
    // Count total colors
    $color_query = "
        SELECT COUNT(DISTINCT mcp.id) as total
        FROM master_color_panel_semarang mcp
    ";
    
    if ($buyer_id > 0) {
        $color_query .= " WHERE mcp.buyer_id = ?";
    }
    
    $color_stmt = $conn->prepare($color_query);
    if ($buyer_id > 0) {
        $color_stmt->bind_param("i", $buyer_id);
    }
    $color_stmt->execute();
    $color_result = $color_stmt->get_result();
    $total_colors = $color_result->fetch_assoc()['total'];
    $color_stmt->close();
    
    echo json_encode([
        'success' => true,
        'total_items' => $total_items,
        'total_colors' => $total_colors,
        'buyer_name' => $buyer_name
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>