<?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');

// Function to send JSON response with mobile-optimized formatting
function sendJSONResponse($success, $message, $item = null) {
    header('Content-Type: application/json');
    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    
    // Optimize message length for mobile displays
    if (!$success && strlen($message) > 150) {
        $message = substr($message, 0, 147) . '...';
    }
    
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'item' => $item
    ], JSON_UNESCAPED_UNICODE);
    exit();
}

// Redirect if not borrower user
if (!is_logged_in() || !is_user_type('borrower')) {
    sendJSONResponse(false, 'Akses tidak diizinkan');
}

// Check if code_barang parameter is provided
if (!isset($_GET['kode_barang']) || empty($_GET['kode_barang'])) {
    sendJSONResponse(false, 'Kode barang harus diisi');
}

$kode_barang = trim($_GET['kode_barang']);

// Validate kode_barang format (should match CP.#### pattern)
if (!preg_match('/^CP\.\d{4}$/', $kode_barang)) {
    sendJSONResponse(false, 'Format tidak valid. Gunakan CP.#### (contoh: CP.0001)');
}

try {
    // Search for the item in color_stock_items with all related information
    $stmt = $conn->prepare("
        SELECT 
            csi.id,
            csi.kode_barang,
            csi.status,
            csi.lokasi,
            csi.rack_no,
            csi.tanggal_pembuatan,
            csi.tanggal_kedaluwarsa,
            csi.keterangan,
            cc.component_name,
            mcp.code_color,
            mcp.deskripsi as color_description,
            b.nama_buyer,
            b.kode_buyer,
            col.nama_collection
        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
        JOIN collections col ON mcp.collection_id = col.id
        WHERE csi.kode_barang = ?
        LIMIT 1
    ");
    
    $stmt->bind_param("s", $kode_barang);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        $stmt->close();
        sendJSONResponse(false, 'Code barang tidak ditemukan di database');
    }
    
    $item = $result->fetch_assoc();
    $stmt->close();
    
    // Check if item can be borrowed based on status
    $restricted_statuses = ['Expired', 'Hilang', 'Dipinjam'];
    if (in_array($item['status'], $restricted_statuses)) {
        if ($item['status'] === 'Dipinjam') {
            sendJSONResponse(false, "Code {$kode_barang} sedang dipinjam dan tidak dapat dipinjam kembali");
        } else {
            sendJSONResponse(false, "Code {$kode_barang} tidak dapat dipinjam (Status: {$item['status']})");
        }
    }
    
    // Check if item is already expired based on tanggal_kedaluwarsa
    if (!empty($item['tanggal_kedaluwarsa'])) {
        $current_date = new DateTime('now', new DateTimeZone('Asia/Jakarta'));
        $expiry_date = new DateTime($item['tanggal_kedaluwarsa'], new DateTimeZone('Asia/Jakarta'));
        
        if ($current_date > $expiry_date) {
            // Update status to Expired if past expiry date
            $update_stmt = $conn->prepare("UPDATE color_stock_items SET status = 'Expired' WHERE id = ?");
            $update_stmt->bind_param("i", $item['id']);
            $update_stmt->execute();
            $update_stmt->close();
            
            sendJSONResponse(false, "Code {$kode_barang} kedaluwarsa pada " . $expiry_date->format('d-m-Y'));
        }
    }
    
    // Get borrower info if item is currently borrowed (this should not happen now due to validation above)
    $borrower_info = null;
    if ($item['status'] === 'Dipinjam') {
        $borrower_stmt = $conn->prepare("
            SELECT 
                bu.username,
                bu.lokasi_posisi,
                st.tanggal_transaksi,
                st.tanggal_pengembalian,
                st.reservation_number,
                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
        ");
        
        $borrower_stmt->bind_param("i", $item['id']);
        $borrower_stmt->execute();
        $borrower_result = $borrower_stmt->get_result();
        
        if ($borrower_result->num_rows > 0) {
            $borrower_data = $borrower_result->fetch_assoc();
            
            try {
                $timezone = new DateTimeZone('Asia/Jakarta');
                $transaksi_date = new DateTime($borrower_data['tanggal_transaksi'], $timezone);
                $pengembalian_date = new DateTime($borrower_data['tanggal_pengembalian'], $timezone);
                
                $borrower_info = [
                    'username' => $borrower_data['username'],
                    'lokasi_posisi' => $borrower_data['lokasi_posisi'],
                    'lokasi_tujuan' => $borrower_data['lokasi_tujuan'],
                    'tanggal_transaksi' => $transaksi_date->format('d-m-Y H:i'),
                    'tanggal_pengembalian' => $pengembalian_date->format('d-m-Y H:i'),
                    'reservation_number' => $borrower_data['reservation_number']
                ];
            } catch (Exception $e) {
                error_log("Error parsing borrower dates: " . $e->getMessage());
            }
        }
        $borrower_stmt->close();
    }
    
    // Format dates for display
    $tanggal_pembuatan_formatted = '';
    $tanggal_kedaluwarsa_formatted = '';
    
    if (!empty($item['tanggal_pembuatan'])) {
        try {
            $pembuatan_date = new DateTime($item['tanggal_pembuatan']);
            $tanggal_pembuatan_formatted = $pembuatan_date->format('d-m-Y');
        } catch (Exception $e) {
            $tanggal_pembuatan_formatted = $item['tanggal_pembuatan'];
        }
    }
    
    if (!empty($item['tanggal_kedaluwarsa'])) {
        try {
            $kedaluwarsa_date = new DateTime($item['tanggal_kedaluwarsa']);
            $tanggal_kedaluwarsa_formatted = $kedaluwarsa_date->format('d-m-Y');
        } catch (Exception $e) {
            $tanggal_kedaluwarsa_formatted = $item['tanggal_kedaluwarsa'];
        }
    }
    
    // Prepare item data for response with mobile-optimized field names
    $item_data = [
        'id' => (int)$item['id'],
        'kode_barang' => $item['kode_barang'],
        'status' => $item['status'],
        'lokasi' => $item['lokasi'],
        'rack_no' => $item['rack_no'] ?: '-',
        'component_name' => $item['component_name'],
        'color_code' => $item['code_color'],
        'color_description' => $item['color_description'],
        'buyer_name' => $item['nama_buyer'],
        'buyer_code' => $item['kode_buyer'],
        'collection_name' => $item['nama_collection'],
        'tanggal_pembuatan' => $tanggal_pembuatan_formatted,
        'tanggal_kedaluwarsa' => $tanggal_kedaluwarsa_formatted,
        'keterangan' => $item['keterangan'] ?: '-',
        'borrower_info' => $borrower_info
    ];
    
    // Detect if request is from mobile (simple detection)
    $isMobile = isset($_SERVER['HTTP_USER_AGENT']) && 
                (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false || 
                 strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false ||
                 strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') !== false);
    
    // Generate mobile-optimized success message
    if ($isMobile) {
        // Shorter message for mobile
        $success_message = "{$kode_barang}: {$item['nama_buyer']} - {$item['code_color']} ({$item['component_name']})";
        
        // Add compact status info
        if ($item['status'] === 'Rusak') {
            $success_message .= " [RUSAK]";
        } elseif ($item['status'] === 'Renew') {
            $success_message .= " [RENEW]";
        }
        
        // Add rack info if available
        if (!empty($item['rack_no'])) {
            $success_message .= " - Rack: {$item['rack_no']}";
        }
    } else {
        // Full message for desktop
        $success_message = "Code barang {$kode_barang} ditemukan: {$item['nama_buyer']} - {$item['code_color']} ({$item['component_name']})";
        
        // Add status-specific information
        if ($item['status'] === 'Rusak') {
            $success_message .= " - Status: RUSAK (kualitas warna mungkin kurang bagus)";
        } elseif ($item['status'] === 'Renew') {
            $success_message .= " - Status: RENEW (perlu diperbaharui)";
        }
        
        // Add rack information if available
        if (!empty($item['rack_no'])) {
            $success_message .= " - Rack: {$item['rack_no']}";
        }
    }
    
    // Log activity with device info
    $device_info = $isMobile ? '[Mobile Request]' : '';
    log_activity($conn, $_SESSION['user_id'], 'borrower', 'Code Validation', 
        "borrower validated code barang: {$kode_barang} - Found: {$item['nama_buyer']} {$item['code_color']} ({$item['component_name']}) {$device_info}");
    
    sendJSONResponse(true, $success_message, $item_data);
    
} catch (Exception $e) {
    error_log("Error in validate_code_barang.php: " . $e->getMessage());
    
    // Mobile-friendly error message
    $error_message = isset($_SERVER['HTTP_USER_AGENT']) && 
                    (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false) 
                    ? 'Terjadi kesalahan sistem. Coba lagi.' 
                    : 'Terjadi kesalahan sistem saat memvalidasi kode barang. Silakan coba lagi.';
    
    sendJSONResponse(false, $error_message);
}
?>