<?php
// Start session
session_start();

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

// Redirect if not admin
if (!is_logged_in() || !is_user_type('admin')) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Unauthorized access']);
    exit();
}

// Check if buyer_id is provided
if (!isset($_GET['buyer_id']) || empty($_GET['buyer_id'])) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Buyer ID is required']);
    exit();
}

$buyer_id = intval($_GET['buyer_id']);

// Get color codes for the specified buyer
$color_query = "SELECT id, code_color FROM master_color_panel WHERE buyer_id = ? ORDER BY code_color";
$color_stmt = $conn->prepare($color_query);
$color_stmt->bind_param("i", $buyer_id);
$color_stmt->execute();
$color_result = $color_stmt->get_result();

$colors = [];
while ($color = $color_result->fetch_assoc()) {
    $colors[] = $color;
}
$color_stmt->close();

// Log the activity
$admin_id = $_SESSION['user_id'];
log_activity($conn, $admin_id, 'admin', 'Get Color Codes', 'Admin fetched color codes for buyer ID: ' . $buyer_id);

// Return JSON response
header('Content-Type: application/json');
echo json_encode(['colors' => $colors]);
exit();