<?php
// Start session
session_start();

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

// Set timezone to Indonesia (WIB/WITA/WIT - adjust according to your location)
date_default_timezone_set('Asia/Jakarta'); // Use Asia/Makassar for WITA or Asia/Jayapura for WIT

// Redirect if not borrower user
if (!is_logged_in() || !is_user_type('borrower')) {
    header('HTTP/1.1 403 Forbidden');
    echo json_encode(['error' => 'Unauthorized access']);
    exit();
}

// Validate input
if (!isset($_GET['item_id']) || empty($_GET['item_id'])) {
    header('HTTP/1.1 400 Bad Request');
    echo json_encode(['error' => 'Item ID is required']);
    exit();
}

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

// Create timezone object for consistent datetime handling
$timezone = new DateTimeZone('Asia/Jakarta'); // Adjust this for your timezone

// Fetch borrower info for the selected item - without duration fields
$stmt = $conn->prepare("
    SELECT 
        bu.username,
        bu.lokasi_posisi,
        st.tanggal_transaksi,
        st.tanggal_pengembalian,
        ti.lokasi_tujuan
    FROM transaction_items ti
    JOIN stock_transactions st ON ti.transaction_id = st.id
    JOIN borrower_users bu ON st.borrower_id = bu.id
    WHERE ti.stock_item_id = ? 
    AND st.status = 'Disetujui'
    AND st.status_peminjaman = 'Dipinjam'
    AND ti.dikembalikan = 0
    ORDER BY st.tanggal_transaksi DESC
    LIMIT 1
");

$stmt->bind_param("i", $item_id);
$stmt->execute();
$result = $stmt->get_result();

if ($row = $result->fetch_assoc()) {
    // Format dates for display with proper timezone
    try {
        $transaksiDateTime = new DateTime($row['tanggal_transaksi'], $timezone);
        $pengembalianDateTime = new DateTime($row['tanggal_pengembalian'], $timezone);
        
        // Calculate duration from actual dates
        $durationSeconds = $pengembalianDateTime->getTimestamp() - $transaksiDateTime->getTimestamp();
        $durationHours = $durationSeconds / 3600;
        
        // Format duration based on length
        if ($durationHours < 24) {
            $durationText = number_format($durationHours, 1) . ' jam';
        } else {
            $durationDays = $durationHours / 24;
            $durationText = number_format($durationDays, 1) . ' hari';
        }
        
        $borrower_info = [
            'username' => $row['username'],
            'lokasi_posisi' => $row['lokasi_posisi'],
            'lokasi_tujuan' => $row['lokasi_tujuan'],
            'tanggal_transaksi' => $transaksiDateTime->format('d-m-Y H:i'),
            'tanggal_pengembalian' => $pengembalianDateTime->format('d-m-Y H:i'),
            'duration' => $durationText,
            'duration_hours' => $durationHours
        ];
    } catch (Exception $e) {
        // If date parsing fails, provide fallback
        $borrower_info = [
            'username' => $row['username'],
            'lokasi_posisi' => $row['lokasi_posisi'],
            'lokasi_tujuan' => $row['lokasi_tujuan'],
            'tanggal_transaksi' => 'Format tanggal tidak valid',
            'tanggal_pengembalian' => 'Format tanggal tidak valid',
            'duration' => 'Tidak dapat dihitung',
            'duration_hours' => 0
        ];
    }
} else {
    // If no active borrower found, try finding the most recent transaction for this item
    $stmt = $conn->prepare("
        SELECT 
            bu.username,
            bu.lokasi_posisi,
            st.tanggal_transaksi,
            st.tanggal_pengembalian,
            st.status,
            st.status_peminjaman,
            ti.lokasi_tujuan
        FROM transaction_items ti
        JOIN stock_transactions st ON ti.transaction_id = st.id
        JOIN borrower_users bu ON st.borrower_id = bu.id
        WHERE ti.stock_item_id = ? 
        ORDER BY st.tanggal_transaksi DESC
        LIMIT 1
    ");
    
    $stmt->bind_param("i", $item_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        // Format dates for display with proper timezone
        try {
            $transaksiDateTime = new DateTime($row['tanggal_transaksi'], $timezone);
            $pengembalianDateTime = new DateTime($row['tanggal_pengembalian'], $timezone);
            
            // Calculate duration from actual dates
            $durationSeconds = $pengembalianDateTime->getTimestamp() - $transaksiDateTime->getTimestamp();
            $durationHours = $durationSeconds / 3600;
            
            // Format duration based on length
            if ($durationHours < 24) {
                $durationText = number_format($durationHours, 1) . ' jam';
            } else {
                $durationDays = $durationHours / 24;
                $durationText = number_format($durationDays, 1) . ' hari';
            }
            
            $borrower_info = [
                'username' => $row['username'],
                'lokasi_posisi' => $row['lokasi_posisi'],
                'lokasi_tujuan' => $row['lokasi_tujuan'],
                'tanggal_transaksi' => $transaksiDateTime->format('d-m-Y H:i'),
                'tanggal_pengembalian' => $pengembalianDateTime->format('d-m-Y H:i'),
                'duration' => $durationText,
                'duration_hours' => $durationHours,
                'transaction_status' => $row['status'],
                'borrowing_status' => $row['status_peminjaman']
            ];
        } catch (Exception $e) {
            // If date parsing fails, provide fallback
            $borrower_info = [
                'username' => $row['username'],
                'lokasi_posisi' => $row['lokasi_posisi'],
                'lokasi_tujuan' => $row['lokasi_tujuan'],
                'tanggal_transaksi' => 'Format tanggal tidak valid',
                'tanggal_pengembalian' => 'Format tanggal tidak valid',
                'duration' => 'Tidak dapat dihitung',
                'duration_hours' => 0,
                'transaction_status' => $row['status'],
                'borrowing_status' => $row['status_peminjaman']
            ];
        }
    } else {
        // No transactions found for this item
        $borrower_info = [
            'username' => 'Tidak ada',
            'lokasi_posisi' => 'Tidak ada',
            'lokasi_tujuan' => 'Tidak ada',
            'tanggal_transaksi' => 'Tidak ada',
            'tanggal_pengembalian' => 'Tidak ada',
            'duration' => 'Tidak ada',
            'duration_hours' => 0
        ];
    }
}

// Get status from color_stock_items
$stmt = $conn->prepare("
    SELECT status FROM color_stock_items WHERE id = ?
");
$stmt->bind_param("i", $item_id);
$stmt->execute();
$result = $stmt->get_result();

if ($status_row = $result->fetch_assoc()) {
    $borrower_info['item_status'] = $status_row['status'];
} else {
    $borrower_info['item_status'] = 'Unknown';
}

// Get color code information for better context
$stmt = $conn->prepare("
    SELECT 
        csi.kode_barang,
        cc.component_name,
        mcp.code_color,
        mcp.deskripsi,
        b.nama_buyer
    FROM color_stock_items csi
    JOIN color_components cc ON csi.component_id = cc.id
    JOIN master_color_panel mcp ON csi.color_id = mcp.id
    JOIN buyers b ON mcp.buyer_id = b.id
    WHERE csi.id = ?
");
$stmt->bind_param("i", $item_id);
$stmt->execute();
$result = $stmt->get_result();

if ($item_info = $result->fetch_assoc()) {
    $borrower_info['kode_barang'] = $item_info['kode_barang'];
    $borrower_info['component_name'] = $item_info['component_name'];
    $borrower_info['color_code'] = $item_info['code_color'];
    $borrower_info['color_description'] = $item_info['deskripsi'];
    $borrower_info['buyer_name'] = $item_info['nama_buyer'];
}

// Add current server time for debugging timezone issues
$current_time = new DateTime('now', $timezone);
$borrower_info['current_server_time'] = $current_time->format('d-m-Y H:i:s');
$borrower_info['server_timezone'] = $timezone->getName();

// Close statement
$stmt->close();

// Return the data as JSON
header('Content-Type: application/json');
echo json_encode($borrower_info);
exit();
?>