<?php
session_start();

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

// Redirect if not admin
if (!is_logged_in() || !is_user_type('admin')) {
    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);

// UPDATED: Get transaction data with enhanced query
$transaction_query = "
    SELECT st.*, bu.username as borrower_name, bu.lokasi_posisi, c.nama_collection_semarang, 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_semarang st 
    JOIN borrower_users_semarang bu ON st.borrower_id = bu.id 
    LEFT JOIN collection_semarangs c ON st.collection_semarang_id = c.id 
    LEFT JOIN buyers_semarang b ON c.buyer_id = b.id 
    LEFT JOIN transaction_items_semarang 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();
}

// UPDATED: Get transaction items with enhanced information including overdue status and selectability
$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,
           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 is_selectable
    FROM transaction_items_semarang ti 
    JOIN color_stock_items_semarang csi ON ti.stock_item_id = csi.id 
    JOIN master_color_panel_semarang mcp ON csi.color_id = mcp.id
    JOIN color_components_semarang cc ON csi.component_id = cc.id
    JOIN buyers_semarang b ON mcp.buyer_id = b.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 = [];

while ($item = $items_result->fetch_assoc()) {
    // 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;
    }
    
    // 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 selection information
    $item['bulk_selection'] = [
        'is_selectable' => (bool)$item['is_selectable'],
        'selection_reason' => '',
        'can_approve' => $item['quantity_approved'] === null,
        'can_reject' => $item['quantity_approved'] === null,
        'can_onprocess' => $item['quantity_approved'] === null
    ];
    
    // Determine why item is or isn't selectable
    if ($item['quantity_approved'] !== null) {
        $item['bulk_selection']['selection_reason'] = 'Item sudah diproses';
    } elseif ($item['item_status'] !== 'Tersedia') {
        $item['bulk_selection']['selection_reason'] = 'Item tidak tersedia (Status: ' . $item['item_status'] . ')';
    } else {
        $item['bulk_selection']['selection_reason'] = 'Item dapat dipilih untuk aksi massal';
    }
    
    $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 including bulk selection stats
$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; 
    })),
    // NEW: Bulk selection statistics
    'selectable_items' => count(array_filter($items, function($item) { 
        return $item['is_selectable'] == 1; 
    })),
    'pending_approval' => count(array_filter($items, function($item) { 
        return $item['quantity_approved'] === null; 
    })),
    'available_for_approval' => count(array_filter($items, function($item) { 
        return $item['quantity_approved'] === null && $item['item_status'] === 'Tersedia'; 
    })),
    'unavailable_for_approval' => count(array_filter($items, function($item) { 
        return $item['quantity_approved'] === null && $item['item_status'] !== 'Tersedia'; 
    }))
];

// Log activity with enhanced information
$log_details = "Admin 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 ($summary_stats['selectable_items'] > 0) {
    $log_details .= " - {$summary_stats['selectable_items']} items available for bulk action";
}

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

// UPDATED: Return enhanced JSON response with bulk selection support
header('Content-Type: application/json');
echo json_encode([
    'status' => 'success',
    'transaction' => $transaction,
    'items' => $items,
    'metadata' => $summary_stats,
    '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
        ],
        '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'))
        ],
        // NEW: Bulk selection summary
        'bulk_selection' => [
            'total_selectable' => $summary_stats['selectable_items'],
            'pending_approval' => $summary_stats['pending_approval'],
            'available_for_approval' => $summary_stats['available_for_approval'],
            'unavailable_for_approval' => $summary_stats['unavailable_for_approval'],
            'has_bulk_actions_available' => $summary_stats['selectable_items'] > 1,
            'selection_breakdown' => [
                'tersedia' => count(array_filter($items, function($item) { 
                    return $item['quantity_approved'] === null && $item['item_status'] === 'Tersedia'; 
                })),
                'dipinjam' => count(array_filter($items, function($item) { 
                    return $item['quantity_approved'] === null && $item['item_status'] === 'Dipinjam'; 
                })),
                'rusak' => count(array_filter($items, function($item) { 
                    return $item['quantity_approved'] === null && $item['item_status'] === 'Rusak'; 
                })),
                'expired' => count(array_filter($items, function($item) { 
                    return $item['quantity_approved'] === null && $item['item_status'] === 'Expired'; 
                })),
                'hilang' => count(array_filter($items, function($item) { 
                    return $item['quantity_approved'] === null && $item['item_status'] === 'Hilang'; 
                }))
            ]
        ]
    ]
]);
exit();
?>