<?php
// Start session
session_start();

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

// Set header untuk JSON response
header('Content-Type: application/json');

// Check if user is IT
if (!is_logged_in() || !is_user_type('it')) {
    echo json_encode([
        'success' => false,
        'message' => 'Akses tidak diizinkan'
    ]);
    exit();
}

// Get filter parameters
$filter_lokasi = isset($_GET['lokasi_posisi']) ? trim($_GET['lokasi_posisi']) : '';
$search_nik = isset($_GET['search_nik']) ? trim($_GET['search_nik']) : '';
$filter_kondisi = isset($_GET['kondisi_kembali']) ? trim($_GET['kondisi_kembali']) : '';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 25;
$offset = ($page - 1) * $limit;

try {
    // Check if only stats requested
    if (isset($_GET['stats_only']) && $_GET['stats_only'] == '1') {
        // Get statistics for kondisi
        $stats_query = "
            SELECT 
                ti.kondisi_kembali,
                COUNT(*) as total
            FROM transaction_items_semarang ti
            JOIN stock_transactions_semarang st ON ti.transaction_id = st.id
            JOIN borrower_users_semarang bu ON st.borrower_id = bu.id
            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 buyers_semarang b ON mcp.buyer_id = b.id
            JOIN color_components_semarang cc ON csi.component_id = cc.id
            WHERE ti.dikembalikan = 1 
            AND ti.tanggal_kembali IS NOT NULL
        ";

        $stats_params = [];
        $stats_types = "";

        // Add filters for stats
        if (!empty($filter_lokasi)) {
            $stats_query .= " AND bu.lokasi_posisi = ?";
            $stats_params[] = $filter_lokasi;
            $stats_types .= "s";
        }

        if (!empty($search_nik)) {
            $stats_query .= " AND bu.nik LIKE ?";
            $stats_params[] = "%{$search_nik}%";
            $stats_types .= "s";
        }

        if (!empty($filter_kondisi)) {
            $stats_query .= " AND ti.kondisi_kembali = ?";
            $stats_params[] = $filter_kondisi;
            $stats_types .= "s";
        }

        $stats_query .= " GROUP BY ti.kondisi_kembali";

        $stats_stmt = $conn->prepare($stats_query);
        if (!empty($stats_params)) {
            $stats_stmt->bind_param($stats_types, ...$stats_params);
        }
        $stats_stmt->execute();
        $stats_result = $stats_stmt->get_result();

        $stats = ['baik' => 0, 'rusak' => 0, 'hilang' => 0];
        while ($row = $stats_result->fetch_assoc()) {
            $kondisi = strtolower($row['kondisi_kembali']);
            $stats[$kondisi] = $row['total'];
        }

        echo json_encode([
            'success' => true,
            'stats' => $stats
        ]);
        exit();
    }
    // Base query untuk menghitung total data
    $count_query = "
        SELECT COUNT(*) as total
        FROM transaction_items_semarang ti
        JOIN stock_transactions_semarang st ON ti.transaction_id = st.id
        JOIN borrower_users_semarang bu ON st.borrower_id = bu.id
        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 buyers_semarang b ON mcp.buyer_id = b.id
        JOIN color_components_semarang cc ON csi.component_id = cc.id
        WHERE ti.dikembalikan = 1 
        AND ti.tanggal_kembali IS NOT NULL
    ";

    // Base query untuk mengambil data
    $data_query = "
        SELECT 
            ti.id as item_id,
            ti.tanggal_kembali,
            ti.kondisi_kembali,
            ti.catatan,
            ti.foto_bukti,
            ti.foto_pengembalian,
            ti.status_waktu,
            st.reservation_number,
            st.tanggal_transaksi,
            st.tanggal_pengembalian,
            bu.username as borrower_username,
            bu.nama_borrower,
            bu.nik,
            bu.lokasi_posisi,
            mcp.code_color,
            mcp.deskripsi as color_description,
            b.nama_buyer,
            cc.component_name,
            csi.kode_barang,
            csi.stock_number,
            csi.rack_no
        FROM transaction_items_semarang ti
        JOIN stock_transactions_semarang st ON ti.transaction_id = st.id
        JOIN borrower_users_semarang bu ON st.borrower_id = bu.id
        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 buyers_semarang b ON mcp.buyer_id = b.id
        JOIN color_components_semarang cc ON csi.component_id = cc.id
        WHERE ti.dikembalikan = 1 
        AND ti.tanggal_kembali IS NOT NULL
    ";

    $params = [];
    $types = "";

    // Add location filter
    if (!empty($filter_lokasi)) {
        $count_query .= " AND bu.lokasi_posisi = ?";
        $data_query .= " AND bu.lokasi_posisi = ?";
        $params[] = $filter_lokasi;
        $types .= "s";
    }

    // Add NIK search filter
    if (!empty($search_nik)) {
        $count_query .= " AND bu.nik LIKE ?";
        $data_query .= " AND bu.nik LIKE ?";
        $params[] = "%{$search_nik}%";
        $types .= "s";
    }

    // Add kondisi filter
    if (!empty($filter_kondisi)) {
        $count_query .= " AND ti.kondisi_kembali = ?";
        $data_query .= " AND ti.kondisi_kembali = ?";
        $params[] = $filter_kondisi;
        $types .= "s";
    }

    // Get total count
    $count_stmt = $conn->prepare($count_query);
    if (!empty($params)) {
        $count_stmt->bind_param($types, ...$params);
    }
    $count_stmt->execute();
    $count_result = $count_stmt->get_result();
    $total_data = $count_result->fetch_assoc()['total'];
    $total_pages = ceil($total_data / $limit);

    // Get data with pagination
    $data_query .= " ORDER BY ti.tanggal_kembali DESC LIMIT ? OFFSET ?";
    $params[] = $limit;
    $params[] = $offset;
    $types .= "ii";

    $stmt = $conn->prepare($data_query);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();

    // Generate table HTML
    $html = '<table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Reservasi</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Peminjam</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Barang</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal Kembali</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kondisi</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status Waktu</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Foto Bukti</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Foto Pengembalian</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Catatan</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">';

    if ($result->num_rows > 0) {
        $no = $offset + 1;
        while ($row = $result->fetch_assoc()) {
            $html .= '<tr class="hover:bg-gray-50">
                        <!-- No -->
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">' . $no . '</td>

                        <!-- Reservasi -->
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">' . htmlspecialchars($row['reservation_number']) . '</div>
                            <div class="text-sm text-gray-500">
                                Pinjam: ' . date('d/m/Y H:i', strtotime($row['tanggal_transaksi'])) . '
                            </div>
                        </td>

                        <!-- Peminjam -->
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">' . htmlspecialchars($row['nama_borrower']) . '</div>
                            <div class="text-sm text-gray-500">NIK: ' . htmlspecialchars($row['nik']) . '</div>
                            <div class="text-sm text-gray-500">' . htmlspecialchars($row['lokasi_posisi']) . '</div>
                        </td>

                        <!-- Barang -->
                        <td class="px-6 py-4">
                            <div class="text-sm font-medium text-gray-900">
                                ' . htmlspecialchars($row['nama_buyer'] . ' ' . $row['code_color']) . '
                            </div>
                            <div class="text-sm text-gray-500">' . htmlspecialchars($row['component_name']) . '</div>
                            <div class="text-sm text-gray-500">
                                ' . htmlspecialchars($row['kode_barang']) . ' - Rack: ' . htmlspecialchars($row['rack_no']) . '
                            </div>
                        </td>

                        <!-- Tanggal Kembali -->
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">
                                ' . date('d/m/Y', strtotime($row['tanggal_kembali'])) . '
                            </div>
                            <div class="text-sm text-gray-500">
                                ' . date('H:i:s', strtotime($row['tanggal_kembali'])) . '
                            </div>
                        </td>

                        <!-- Kondisi -->
                        <td class="px-6 py-4 whitespace-nowrap">';

            // Kondisi badge
            $kondisi_color = '';
            switch($row['kondisi_kembali']) {
                case 'Baik':
                    $kondisi_color = 'bg-green-100 text-green-800';
                    break;
                case 'Rusak':
                    $kondisi_color = 'bg-red-100 text-red-800';
                    break;
                case 'Hilang':
                    $kondisi_color = 'bg-yellow-100 text-yellow-800';
                    break;
                default:
                    $kondisi_color = 'bg-gray-100 text-gray-800';
            }

            $html .= '<span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full ' . $kondisi_color . '">
                        ' . htmlspecialchars($row['kondisi_kembali']) . '
                      </span>
                      </td>

                      <!-- Status Waktu -->
                      <td class="px-6 py-4 whitespace-nowrap">';

            // Status waktu badge
            $status_color = '';
            $status_text = '';
            switch($row['status_waktu']) {
                case 'tepat':
                    $status_color = 'bg-green-100 text-green-800';
                    $status_text = 'Tepat Waktu';
                    break;
                case 'overdue':
                    $status_color = 'bg-red-100 text-red-800';
                    $status_text = 'Terlambat';
                    break;
                default:
                    $status_color = 'bg-gray-100 text-gray-800';
                    $status_text = 'Normal';
            }

            $html .= '<span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full ' . $status_color . '">
                        ' . $status_text . '
                      </span>
                      </td>

                      <!-- Foto Bukti -->
                      <td class="px-6 py-4 whitespace-nowrap text-center">';

            if (!empty($row['foto_bukti'])) {
                $html .= '<button onclick="showPhoto(\'' . htmlspecialchars($row['foto_bukti']) . '\', \'Foto Bukti Kondisi\', \'Foto kondisi barang saat dikembalikan - ' . htmlspecialchars($row['kode_barang']) . '\')" 
                                 class="text-blue-600 hover:text-blue-800">
                            <i class="fas fa-image text-lg"></i>
                            <div class="text-xs">Lihat Foto</div>
                          </button>';
            } else {
                $html .= '<span class="text-gray-400">
                            <i class="fas fa-times"></i>
                            <div class="text-xs">Tidak Ada</div>
                          </span>';
            }

            $html .= '</td>

                      <!-- Foto Pengembalian -->
                      <td class="px-6 py-4 whitespace-nowrap text-center">';

            if (!empty($row['foto_pengembalian'])) {
                $html .= '<button onclick="showPhoto(\'' . htmlspecialchars($row['foto_pengembalian']) . '\', \'Foto Pengembalian\', \'Foto dokumentasi pengembalian barang ke rack - ' . htmlspecialchars($row['kode_barang']) . '\')" 
                                 class="text-green-600 hover:text-green-800">
                            <i class="fas fa-camera text-lg"></i>
                            <div class="text-xs">Lihat Foto</div>
                          </button>';
            } else {
                $html .= '<span class="text-gray-400">
                            <i class="fas fa-times"></i>
                            <div class="text-xs">Tidak Ada</div>
                          </span>';
            }

            $html .= '</td>

                      <!-- Catatan -->
                      <td class="px-6 py-4">
                          <div class="text-sm text-gray-900 max-w-xs overflow-hidden">';

            if (!empty($row['catatan'])) {
                $html .= '<div title="' . htmlspecialchars($row['catatan']) . '" class="truncate">
                            ' . htmlspecialchars(substr($row['catatan'], 0, 50));
                if (strlen($row['catatan']) > 50) {
                    $html .= '...';
                }
                $html .= '</div>';
            } else {
                $html .= '<span class="text-gray-400">-</span>';
            }

            $html .= '</div></td></tr>';
            $no++;
        }
    } else {
        $html .= '<tr>
                    <td colspan="10" class="px-6 py-8 text-center text-gray-500">
                        <i class="fas fa-inbox text-4xl mb-4 text-gray-300"></i>
                        <div class="text-lg font-medium">Tidak ada data history pengembalian</div>
                        <div class="text-sm">';

        if (!empty($filter_lokasi) || !empty($search_nik) || !empty($filter_kondisi)) {
            $html .= 'Coba ubah filter atau kriteria pencarian';
        } else {
            $html .= 'Belum ada barang yang dikembalikan';
        }

        $html .= '</div>
                    </td>
                  </tr>';
    }

    $html .= '</tbody></table>';

    // Return JSON response
    echo json_encode([
        'success' => true,
        'html' => $html,
        'totalData' => $total_data,
        'totalPages' => $total_pages,
        'currentPage' => $page,
        'limit' => $limit
    ]);

    $stmt->close();

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Terjadi kesalahan saat memuat data: ' . $e->getMessage()
    ]);
}
?>