<?php
session_start();

// Include database connection and helper functions
require_once "../config/connection.php";
require_once "transaction_actions_it.php";

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

// Validate transaction ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'Invalid transaction ID']);
    exit();
}

$transaction_id = intval($_GET['id']);

// UPDATED: Update overdue status for borrowed items automatically before fetching data
updateOverdueStatus($conn);

// FIXED: Get transaction data with enhanced query including borrower location
$transaction_query = "
    SELECT st.*, bu.username as borrower_name, bu.lokasi_posisi, c.nama_collection, b.nama_buyer,
           COUNT(ti.id) as total_items,
           COUNT(CASE WHEN ti.dikembalikan = 1 THEN 1 END) as returned_items,
           COUNT(CASE WHEN ti.status_waktu = 'overdue' THEN 1 END) as overdue_items,
           COUNT(CASE WHEN ti.status_waktu = 'tepat' THEN 1 END) as on_time_items
    FROM stock_transactions st 
    JOIN borrower_users bu ON st.borrower_id = bu.id 
    LEFT JOIN collections c ON st.collection_id = c.id 
    LEFT JOIN buyers b ON c.buyer_id = b.id 
    LEFT JOIN transaction_items ti ON st.id = ti.transaction_id
    WHERE st.id = ?
    GROUP BY st.id
";

$stmt = $conn->prepare($transaction_query);
$stmt->bind_param("i", $transaction_id);
$stmt->execute();
$transaction_result = $stmt->get_result();
$transaction = $transaction_result->fetch_assoc();
$stmt->close();

if (!$transaction) {
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'Transaction not found']);
    exit();
}

// FIXED: Get transaction items with complete information including lokasi_tujuan
$items_query = "
    SELECT ti.*, csi.kode_barang, csi.component_id, csi.color_id, csi.keterangan, csi.status as item_status,
           csi.lokasi as current_lokasi, csi.rack_no, csi.tanggal_pembuatan, csi.tanggal_kedaluwarsa,
           mcp.code_color, mcp.deskripsi as color_description, cc.component_name, b.nama_buyer,
           bu.lokasi_posisi as borrower_location,
           CASE 
               WHEN ti.dikembalikan = 1 THEN TIMESTAMPDIFF(HOUR, ?, ti.tanggal_kembali)
               ELSE TIMESTAMPDIFF(HOUR, ?, NOW())
           END as hours_difference,
           CASE 
               WHEN ti.dikembalikan = 0 AND NOW() > DATE_ADD(?, INTERVAL 15 MINUTE) THEN 1
               ELSE 0
           END as is_currently_overdue,
           CASE 
               WHEN ti.quantity_approved IS NULL AND csi.status = 'Tersedia' THEN 1
               ELSE 0
           END as can_bulk_select,
           CASE 
               WHEN ti.quantity_approved IS NULL AND csi.status != 'Tersedia' THEN 1
               ELSE 0
           END as is_unavailable_for_bulk
    FROM transaction_items ti 
    JOIN color_stock_items csi ON ti.stock_item_id = csi.id 
    JOIN master_color_panel mcp ON csi.color_id = mcp.id
    JOIN color_components cc ON csi.component_id = cc.id
    JOIN buyers b ON mcp.buyer_id = b.id
    JOIN stock_transactions st ON ti.transaction_id = st.id
    JOIN borrower_users bu ON st.borrower_id = bu.id
    WHERE ti.transaction_id = ?
    ORDER BY ti.id ASC
";

$stmt = $conn->prepare($items_query);
$stmt->bind_param("sssi", 
    $transaction['tanggal_pengembalian'], 
    $transaction['tanggal_pengembalian'],
    $transaction['tanggal_pengembalian'],
    $transaction_id
);
$stmt->execute();
$items_result = $stmt->get_result();
$items = [];

// NEW: Count items for bulk action statistics
$bulk_action_stats = [
    'total_pending' => 0,
    'available_for_bulk' => 0,
    'unavailable_for_bulk' => 0,
    'available_items' => [],
    'unavailable_items' => []
];

while ($item = $items_result->fetch_assoc()) {
    // FIXED: Ensure lokasi_tujuan is properly set
    if (empty($item['lokasi_tujuan'])) {
        $item['lokasi_tujuan'] = $item['borrower_location'];
    }
    
    // UPDATED: Add comprehensive overdue information
    if ($transaction['tanggal_pengembalian']) {
        $expected_return = new DateTime($transaction['tanggal_pengembalian']);
        $tolerance_time = clone $expected_return;
        $tolerance_time->add(new DateInterval('PT15M')); // Add 15 minutes tolerance
        $current_time = new DateTime();
        
        // Enhanced overdue calculations
        $item['expected_return_time'] = $expected_return->format('Y-m-d H:i:s');
        $item['tolerance_deadline'] = $tolerance_time->format('Y-m-d H:i:s');
        $item['is_currently_overdue'] = (!$item['dikembalikan'] && $current_time > $tolerance_time);
        
        // Calculate overdue duration for display
        if ($item['status_waktu'] === 'overdue') {
            $overdue_hours = abs($item['hours_difference']);
            $item['overdue_display'] = [
                'days' => floor($overdue_hours / 24),
                'hours' => $overdue_hours % 24,
                'total_hours' => $overdue_hours
            ];
        }
        
        // Add return status information
        if ($item['dikembalikan']) {
            $return_time = new DateTime($item['tanggal_kembali']);
            $item['returned_early'] = $return_time < $expected_return;
            $item['returned_on_time'] = $return_time <= $tolerance_time;
            $item['returned_late'] = $return_time > $tolerance_time;
        }
    } else {
        $item['expected_return_time'] = null;
        $item['tolerance_deadline'] = null;
        $item['is_currently_overdue'] = false;
    }
    
    // FIXED: Bulk action eligibility and statistics
    if ($item['quantity_approved'] === null) {
        $bulk_action_stats['total_pending']++;
        
        if ($item['can_bulk_select']) {
            $bulk_action_stats['available_for_bulk']++;
            $bulk_action_stats['available_items'][] = [
                'id' => intval($item['id']), // FIXED: Ensure ID is integer
                'kode_barang' => $item['kode_barang'],
                'color_code' => $item['code_color'],
                'component_name' => $item['component_name'],
                'item_status' => $item['item_status'],
                'lokasi_tujuan' => $item['lokasi_tujuan'] // FIXED: Include lokasi_tujuan
            ];
        } elseif ($item['is_unavailable_for_bulk']) {
            $bulk_action_stats['unavailable_for_bulk']++;
            $bulk_action_stats['unavailable_items'][] = [
                'id' => intval($item['id']), // FIXED: Ensure ID is integer
                'kode_barang' => $item['kode_barang'],
                'color_code' => $item['code_color'],
                'component_name' => $item['component_name'],
                'item_status' => $item['item_status'],
                'reason' => 'Item status: ' . $item['item_status']
            ];
        }
    }
    
    // UPDATED: Add status indicators for UI
    $item['status_indicator'] = [
        'class' => '',
        'text' => '',
        'icon' => ''
    ];
    
    if ($item['dikembalikan']) {
        if ($item['status_waktu'] === 'tepat') {
            $item['status_indicator'] = [
                'class' => 'bg-green-100 text-green-800 border-green-200',
                'text' => 'Dikembalikan Tepat Waktu',
                'icon' => 'fas fa-check-circle'
            ];
        } elseif ($item['status_waktu'] === 'overdue') {
            $item['status_indicator'] = [
                'class' => 'bg-red-100 text-red-800 border-red-200',
                'text' => 'Dikembalikan Terlambat',
                'icon' => 'fas fa-exclamation-triangle'
            ];
        } else {
            $item['status_indicator'] = [
                'class' => 'bg-blue-100 text-blue-800 border-blue-200',
                'text' => 'Sudah Dikembalikan',
                'icon' => 'fas fa-check'
            ];
        }
    } else {
        if ($item['is_currently_overdue']) {
            $item['status_indicator'] = [
                'class' => 'bg-red-100 text-red-800 border-red-200',
                'text' => 'Sedang Terlambat',
                'icon' => 'fas fa-clock text-red-500'
            ];
        } else {
            $item['status_indicator'] = [
                'class' => 'bg-yellow-100 text-yellow-800 border-yellow-200',
                'text' => 'Sedang Dipinjam',
                'icon' => 'fas fa-hand-holding'
            ];
        }
    }
    
    // NEW: Add bulk action specific flags
    $item['bulk_action_eligible'] = $item['can_bulk_select'] == 1;
    $item['bulk_action_disabled'] = $item['is_unavailable_for_bulk'] == 1;
    $item['bulk_disabled_reason'] = $item['bulk_action_disabled'] ? 
        "Item tidak tersedia (Status: {$item['item_status']})" : null;
    
    // FIXED: Ensure all necessary fields are included
    $item['id'] = intval($item['id']); // Ensure ID is integer
    $item['transaction_id'] = $transaction_id;
    $item['quantity_requested'] = intval($item['quantity_requested'] ?? 1);
    $item['quantity_approved'] = $item['quantity_approved'] !== null ? intval($item['quantity_approved']) : null;
    
    $items[] = $item;
}
$stmt->close();

// UPDATED: Calculate enhanced duration information
$duration_info = null;
$duration_details = [];

if ($transaction['tanggal_transaksi'] && $transaction['tanggal_pengembalian']) {
    $start_time = new DateTime($transaction['tanggal_transaksi']);
    $end_time = new DateTime($transaction['tanggal_pengembalian']);
    $interval = $start_time->diff($end_time);
    
    // Format duration for display
    if ($interval->days > 0) {
        $duration_info = $interval->days . ' hari ' . $interval->h . ' jam';
        if ($interval->i > 0) {
            $duration_info .= ' ' . $interval->i . ' menit';
        }
    } else {
        $duration_info = $interval->h . ' jam';
        if ($interval->i > 0) {
            $duration_info .= ' ' . $interval->i . ' menit';
        }
    }
    
    $duration_details = [
        'days' => $interval->days,
        'hours' => $interval->h,
        'minutes' => $interval->i,
        'total_hours' => ($interval->days * 24) + $interval->h + ($interval->i / 60)
    ];
}

// Add enhanced transaction information
$transaction['calculated_duration'] = $duration_info;
$transaction['duration_details'] = $duration_details;

// UPDATED: Calculate summary statistics
$summary_stats = [
    'total_items' => count($items),
    'approved_items' => count(array_filter($items, function($item) { 
        return $item['quantity_approved'] > 0; 
    })),
    'returned_items' => count(array_filter($items, function($item) { 
        return $item['dikembalikan'] == 1; 
    })),
    'overdue_items' => count(array_filter($items, function($item) { 
        return $item['status_waktu'] === 'overdue'; 
    })),
    'on_time_returns' => count(array_filter($items, function($item) { 
        return $item['status_waktu'] === 'tepat'; 
    })),
    'currently_overdue' => count(array_filter($items, function($item) { 
        return $item['is_currently_overdue'] == 1; 
    })),
    'pending_return' => count(array_filter($items, function($item) { 
        return $item['dikembalikan'] == 0; 
    })),
    'pending_approval' => count(array_filter($items, function($item) { 
        return $item['quantity_approved'] === null; 
    })),
    'rejected_items' => count(array_filter($items, function($item) { 
        return $item['quantity_approved'] === 0; 
    }))
];

// NEW: Enhanced bulk action recommendations
$bulk_recommendations = [];

if ($bulk_action_stats['available_for_bulk'] > 0) {
    if ($bulk_action_stats['available_for_bulk'] >= 3) {
        $bulk_recommendations[] = [
            'type' => 'bulk_approve',
            'message' => "Anda dapat menyetujui {$bulk_action_stats['available_for_bulk']} item sekaligus dengan fitur aksi massal",
            'icon' => 'fas fa-check-double',
            'color' => 'green'
        ];
    }
    
    if ($bulk_action_stats['unavailable_for_bulk'] > 0) {
        $bulk_recommendations[] = [
            'type' => 'mixed_status',
            'message' => "{$bulk_action_stats['unavailable_for_bulk']} item tidak dapat diproses karena status tidak tersedia",
            'icon' => 'fas fa-exclamation-triangle',
            'color' => 'yellow'
        ];
    }
}

// NEW: Generate bulk action summary
$bulk_action_summary = [
    'has_bulk_eligible_items' => $bulk_action_stats['available_for_bulk'] > 0,
    'recommended_bulk_action' => $bulk_action_stats['available_for_bulk'] >= 2,
    'bulk_efficiency_score' => $bulk_action_stats['total_pending'] > 0 ? 
        round(($bulk_action_stats['available_for_bulk'] / $bulk_action_stats['total_pending']) * 100) : 0,
    'statistics' => $bulk_action_stats,
    'recommendations' => $bulk_recommendations
];

// Log activity with enhanced information for IT user
$log_details = "IT user viewed transaction ID: {$transaction_id} (Reservation: {$transaction['reservation_number']})";
if ($summary_stats['currently_overdue'] > 0) {
    $log_details .= " - Contains {$summary_stats['currently_overdue']} overdue items";
}
if ($bulk_action_stats['available_for_bulk'] > 0) {
    $log_details .= " - {$bulk_action_stats['available_for_bulk']} items available for bulk action";
}

log_activity($conn, $_SESSION['user_id'], 'it', 'View Transaction Details', $log_details);

// FIXED: Debug logging for bulk action data
error_log("=== TRANSACTION DETAILS DEBUG ===");
error_log("Transaction ID: " . $transaction_id);
error_log("Total Items: " . count($items));
error_log("Available for Bulk: " . $bulk_action_stats['available_for_bulk']);
error_log("Available Items IDs: " . json_encode(array_column($bulk_action_stats['available_items'], 'id')));

// UPDATED: Return enhanced JSON response with bulk action support
header('Content-Type: application/json');
echo json_encode([
    'status' => 'success',
    'transaction' => $transaction,
    'items' => $items,
    'metadata' => $summary_stats,
    'bulk_actions' => $bulk_action_summary,
    'summary' => [
        'reservation_number' => $transaction['reservation_number'],
        'borrower_info' => [
            'name' => $transaction['borrower_name'],
            'position' => $transaction['lokasi_posisi']
        ],
        'duration' => [
            'formatted' => $duration_info,
            'details' => $duration_details
        ],
        'status_overview' => [
            'transaction_status' => $transaction['status'],
            'borrowing_status' => $transaction['status_peminjaman'],
            'has_overdue_items' => $summary_stats['overdue_items'] > 0 || $summary_stats['currently_overdue'] > 0,
            'completion_rate' => $summary_stats['total_items'] > 0 ? 
                round(($summary_stats['returned_items'] / $summary_stats['total_items']) * 100, 1) : 0,
            'approval_rate' => $summary_stats['total_items'] > 0 ? 
                round(($summary_stats['approved_items'] / $summary_stats['total_items']) * 100, 1) : 0
        ],
        'timeline' => [
            'borrowed_at' => $transaction['tanggal_transaksi'],
            'due_at' => $transaction['tanggal_pengembalian'],
            'is_overdue_period' => $transaction['tanggal_pengembalian'] && 
                (new DateTime() > new DateTime($transaction['tanggal_pengembalian'] . ' +15 minutes'))
        ],
        'bulk_action_info' => [
            'eligible_items' => $bulk_action_stats['available_for_bulk'],
            'unavailable_items' => $bulk_action_stats['unavailable_for_bulk'],
            'efficiency_score' => $bulk_action_summary['bulk_efficiency_score'],
            'recommended' => $bulk_action_summary['recommended_bulk_action']
        ]
    ]
]);
exit();
?>