<?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();
}

// Get renew history with additional information from all related tables
$history_query = "
    SELECT 
        rch.*,
        DATE_FORMAT(rch.renewed_date, '%d %b %Y %H:%i') AS formatted_renewed_date,
        csi.kode_barang AS new_code,
        mcp.code_color,
        cc.component_name,
        b.nama_buyer,
        b.kode_buyer
    FROM 
        renew_code_history rch
    JOIN 
        color_stock_items csi ON rch.original_id = csi.id
    JOIN 
        master_color_panel mcp ON rch.color_id = mcp.id
    JOIN 
        color_components cc ON rch.component_id = cc.id
    JOIN 
        buyers b ON mcp.buyer_id = b.id
    ORDER BY 
        rch.renewed_date DESC
";

$history_result = $conn->query($history_query);
$history_items = [];

if ($history_result) {
    while ($row = $history_result->fetch_assoc()) {
        // Add any responsive-specific data formatting if needed
        // For example, you might want to shorten very long text for mobile display
        if (strlen($row['component_name']) > 15) {
            $row['component_name_short'] = substr($row['component_name'], 0, 15) . '...';
        } else {
            $row['component_name_short'] = $row['component_name'];
        }
        
        // Format dates for better mobile display
        $row['formatted_renewed_date_short'] = date('d/m/y H:i', strtotime($row['renewed_date']));
        
        $history_items[] = $row;
    }
}

// Log the access
$admin_id = $_SESSION['user_id'];
log_activity($conn, $admin_id, 'admin', 'View Renew History', 'Admin viewed color renew history');

// Prepare response
$response = [
    'history' => $history_items
];

// Return JSON response
header('Content-Type: application/json');
echo json_encode($response);
exit();