<?php
/**
 * bbu_list.php - BBU Management List Page
 * Displays all BBU entries with search, filter, pagination, and export options
 */

ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

session_start();
require_once("../config/config.php");

$allowed_roles = ['store manager', 'admin', 'project manager'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header("Location: ../login.php");
    exit();
}

// Handle Export
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    exportToExcel($conn);
    exit();
}

if (isset($_GET['export']) && $_GET['export'] == 'pdf') {
    exportToPDF($conn);
    exit();
}

// Get filter parameters
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$project_id = $_GET['project_id'] ?? '';
$rate_type = $_GET['rate_type'] ?? '';
$from_date = $_GET['from_date'] ?? '';
$to_date = $_GET['to_date'] ?? '';
$sort_by = $_GET['sort_by'] ?? 'created_at';
$sort_order = $_GET['sort_order'] ?? 'DESC';
$limit = 15;
$offset = ($page - 1) * $limit;

// Build WHERE clause
$where_conditions = [];
$params = [];
$types = "";

if (!empty($search)) {
    $where_conditions[] = "(b.system_description LIKE ? OR b.bbu_no LIKE ? OR b.boq_code LIKE ? OR b.bbu_no LIKE ?)";
    $search_param = "%{$search}%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= "ssss";
}

if (!empty($status)) {
    $where_conditions[] = "b.status = ?";
    $params[] = $status;
    $types .= "s";
}

if (!empty($project_id)) {
    $where_conditions[] = "b.project_id = ?";
    $params[] = $project_id;
    $types .= "i";
}

if (!empty($rate_type)) {
    $where_conditions[] = "b.rate_type = ?";
    $params[] = $rate_type;
    $types .= "s";
}

if (!empty($from_date)) {
    $where_conditions[] = "DATE(b.created_at) >= ?";
    $params[] = $from_date;
    $types .= "s";
}

if (!empty($to_date)) {
    $where_conditions[] = "DATE(b.created_at) <= ?";
    $params[] = $to_date;
    $types .= "s";
}

$where_sql = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";

// Get total count for pagination
$count_sql = "SELECT COUNT(*) as total FROM bbu_master b LEFT JOIN project_master p ON b.project_id = p.id $where_sql";
$count_stmt = $conn->prepare($count_sql);
if (!empty($params)) {
    $count_stmt->bind_param($types, ...$params);
}
$count_stmt->execute();
$total_result = $count_stmt->get_result();
$total_records = $total_result->fetch_assoc()['total'];
$total_pages = ceil($total_records / $limit);

// Fetch BBU records
$sql = "
    SELECT 
        b.*,
        p.project_code,
        p.project_name,
        u.full_name as created_by_name,
        CASE 
            WHEN b.rate_type = 'SITC' THEN b.sitc_amount
            ELSE (b.supply_amount + b.itc_amount)
        END as total_amount,
        (SELECT COUNT(*) FROM bbu_items WHERE bbu_id = b.id) as items_count
    FROM bbu_master b
    LEFT JOIN project_master p ON b.project_id = p.id
    LEFT JOIN users u ON b.created_by = u.id
    $where_sql
    ORDER BY $sort_by $sort_order
    LIMIT ? OFFSET ?
";

$params[] = $limit;
$params[] = $offset;
$types .= "ii";

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

// Fetch projects for filter dropdown
$projects = $conn->query("
    SELECT id, project_code, project_name 
    FROM project_master 
    WHERE project_status IN ('Active', 'In Progress')
    ORDER BY project_name
");

// Get statistics
$stats_sql = "
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'Draft' THEN 1 ELSE 0 END) as draft,
        SUM(CASE WHEN status = 'Submitted' THEN 1 ELSE 0 END) as submitted,
        SUM(CASE WHEN status = 'Approved' THEN 1 ELSE 0 END) as approved,
        SUM(CASE WHEN status = 'Rejected' THEN 1 ELSE 0 END) as rejected,
        SUM(CASE 
            WHEN rate_type = 'SITC' THEN sitc_amount
            ELSE (supply_amount + itc_amount)
        END) as total_value,
        SUM(CASE WHEN status = 'Draft' THEN 
            CASE WHEN rate_type = 'SITC' THEN sitc_amount ELSE (supply_amount + itc_amount) END 
        ELSE 0 END) as draft_value,
        SUM(CASE WHEN status = 'Approved' THEN 
            CASE WHEN rate_type = 'SITC' THEN sitc_amount ELSE (supply_amount + itc_amount) END 
        ELSE 0 END) as approved_value
    FROM bbu_master
";
$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();

// Export functions
function exportToExcel($conn) {
    $sql = "SELECT b.bbu_no, b.created_at, p.project_code, p.project_name, b.system_description, 
                   b.quantity, b.rate_type, 
                   CASE WHEN b.rate_type = 'SITC' THEN b.sitc_amount ELSE (b.supply_amount + b.itc_amount) END as total_amount,
                   b.status, u.full_name as created_by
            FROM bbu_master b
            LEFT JOIN project_master p ON b.project_id = p.id
            LEFT JOIN users u ON b.created_by = u.id
            ORDER BY b.created_at DESC";
    
    $result = $conn->query($sql);
    
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="bbu_list_' . date('Y-m-d') . '.xls"');
    
    echo "BBU No\tDate\tProject Code\tProject Name\tDescription\tQuantity\tRate Type\tTotal Amount\tStatus\tCreated By\n";
    
    while ($row = $result->fetch_assoc()) {
        echo implode("\t", [
            $row['bbu_no'],
            date('d-m-Y', strtotime($row['created_at'])),
            $row['project_code'],
            $row['project_name'],
            strip_tags($row['system_description']),
            $row['quantity'],
            $row['rate_type'],
            number_format($row['total_amount'], 2),
            $row['status'],
            $row['created_by']
        ]) . "\n";
    }
    exit();
}

function exportToPDF($conn) {
    // This would typically use a library like TCPDF or FPDF
    // For now, redirect to Excel export
    header("Location: " . $_SERVER['PHP_SELF'] . "?export=excel");
    exit();
}

// Function to get status badge class
function getStatusBadgeClass($status) {
    switch ($status) {
        case 'Draft': return 'status-draft';
        case 'Submitted': return 'status-submitted';
        case 'Approved': return 'status-approved';
        case 'Rejected': return 'status-rejected';
        default: return 'status-draft';
    }
}

function getStatusIcon($status) {
    switch ($status) {
        case 'Draft': return 'fa-edit';
        case 'Submitted': return 'fa-paper-plane';
        case 'Approved': return 'fa-check-circle';
        case 'Rejected': return 'fa-times-circle';
        default: return 'fa-question-circle';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>BBU List | Budget Updates Management</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);
            color: #f1f5f9;
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1600px;
            margin: 0 auto;
        }

        .glass-card {
            background: rgba(255, 255, 255, 0.08);
            backdrop-filter: blur(12px);
            border-radius: 32px;
            border: 1px solid rgba(255, 255, 255, 0.15);
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, rgba(139, 92, 246, 0.3), rgba(59, 130, 246, 0.2));
            padding: 40px 35px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .header h1 {
            font-size: clamp(24px, 5vw, 36px);
            font-weight: 700;
            background: linear-gradient(135deg, #fff, #c4b5fd);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 20px;
            padding: 30px 35px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .stat-card {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 20px;
            padding: 20px;
            text-align: center;
            transition: all 0.3s;
            cursor: pointer;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .stat-card:hover {
            transform: translateY(-5px);
            background: rgba(255, 255, 255, 0.08);
            border-color: rgba(139, 92, 246, 0.5);
        }

        .stat-icon {
            font-size: 2rem;
            margin-bottom: 10px;
        }

        .stat-value {
            font-size: 1.8rem;
            font-weight: 700;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 0.8rem;
            color: #c4b5fd;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .stat-sub {
            font-size: 0.7rem;
            color: #9ca3af;
            margin-top: 5px;
        }

        /* Toolbar */
        .toolbar {
            padding: 25px 35px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .filters {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            flex: 1;
        }

        .filter-group {
            position: relative;
            min-width: 180px;
        }

        .filter-group input,
        .filter-group select {
            width: 100%;
            padding: 12px 16px;
            background: rgba(255, 255, 255, 0.08);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 40px;
            color: white;
            font-size: 0.9rem;
            cursor: pointer;
            transition: all 0.3s;
        }
        option{
            color:black;
        }
        .filter-group input:focus,
        .filter-group select:focus {
            outline: none;
            border-color: #8b5cf6;
            background: rgba(255, 255, 255, 0.12);
        }

        .btn-add {
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
            padding: 12px 28px;
            border-radius: 40px;
            text-decoration: none;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            transition: all 0.3s;
            white-space: nowrap;
        }

        .btn-add:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(16, 185, 129, 0.3);
        }

        .btn-export {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            padding: 12px 20px;
            border-radius: 40px;
            text-decoration: none;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }

        .btn-export:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        .btn-reset {
            background: rgba(239, 68, 68, 0.2);
            color: #fca5a5;
            padding: 12px 20px;
            border-radius: 40px;
            text-decoration: none;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }

        .btn-reset:hover {
            background: rgba(239, 68, 68, 0.3);
        }

        /* Table Container */
        .table-container {
            padding: 0 35px 35px;
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th {
            text-align: left;
            padding: 16px;
            background: rgba(139, 92, 246, 0.2);
            font-weight: 600;
            font-size: 0.85rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            cursor: pointer;
            transition: background 0.3s;
            user-select: none;
        }

        th:hover {
            background: rgba(139, 92, 246, 0.3);
        }

        th i {
            margin-left: 5px;
            font-size: 0.7rem;
            opacity: 0.6;
        }

        td {
            padding: 16px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.08);
            font-size: 0.9rem;
        }

        tr:hover {
            background: rgba(255, 255, 255, 0.03);
        }

        /* Status Badges */
        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            border-radius: 40px;
            font-size: 0.75rem;
            font-weight: 600;
            width: fit-content;
        }

        .status-draft {
            background: rgba(245, 158, 11, 0.2);
            color: #fbbf24;
            border: 1px solid #fbbf24;
        }

        .status-submitted {
            background: rgba(59, 130, 246, 0.2);
            color: #60a5fa;
            border: 1px solid #60a5fa;
        }

        .status-approved {
            background: rgba(34, 197, 94, 0.2);
            color: #86efac;
            border: 1px solid #86efac;
        }

        .status-rejected {
            background: rgba(239, 68, 68, 0.2);
            color: #fca5a5;
            border: 1px solid #fca5a5;
        }

        /* Rate Type Badge */
        .rate-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.7rem;
            font-weight: 600;
        }

        .rate-SITC {
            background: rgba(139, 92, 246, 0.3);
            color: #c4b5fd;
        }

        .rate-SITC-plus {
            background: rgba(236, 72, 153, 0.3);
            color: #f9a8d4;
        }

        /* Action Buttons */
        .action-btns {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .action-btn {
            padding: 6px 12px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 0.8rem;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            transition: all 0.2s;
            cursor: pointer;
            border: none;
        }

        .btn-view {
            background: rgba(59, 130, 246, 0.2);
            color: #60a5fa;
        }

        .btn-view:hover {
            background: rgba(59, 130, 246, 0.4);
        }

        .btn-edit {
            background: rgba(234, 179, 8, 0.2);
            color: #fde047;
        }

        .btn-edit:hover {
            background: rgba(234, 179, 8, 0.4);
        }

        .btn-delete {
            background: rgba(239, 68, 68, 0.2);
            color: #f87171;
        }

        .btn-delete:hover {
            background: rgba(239, 68, 68, 0.4);
        }

        /* Pagination */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
            margin-top: 30px;
            flex-wrap: wrap;
        }

        .pagination a, .pagination span {
            padding: 8px 14px;
            background: rgba(255, 255, 255, 0.08);
            border-radius: 8px;
            text-decoration: none;
            color: white;
            transition: all 0.2s;
        }

        .pagination a:hover {
            background: rgba(139, 92, 246, 0.4);
        }

        .pagination .active {
            background: #8b5cf6;
        }

        .pagination .disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }

        .empty-state i {
            font-size: 4rem;
            opacity: 0.3;
            margin-bottom: 20px;
        }

        .empty-state h3 {
            margin-bottom: 10px;
        }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background: linear-gradient(135deg, #1e1b4b, #2e2a5e);
            border-radius: 24px;
            padding: 30px;
            max-width: 500px;
            width: 90%;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .modal-header {
            font-size: 1.5rem;
            margin-bottom: 20px;
        }

        .modal-body {
            margin-bottom: 25px;
        }

        .modal-footer {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
        }

        .modal-btn {
            padding: 10px 20px;
            border-radius: 8px;
            border: none;
            cursor: pointer;
            font-weight: 600;
        }

        .modal-btn-confirm {
            background: #ef4444;
            color: white;
        }

        .modal-btn-cancel {
            background: rgba(255, 255, 255, 0.1);
            color: white;
        }

        /* Toast Notification */
        .toast {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: rgba(34, 197, 94, 0.9);
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            display: none;
            align-items: center;
            gap: 10px;
            z-index: 1100;
            animation: slideIn 0.3s ease;
        }

        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        /* Responsive */
        @media (max-width: 1024px) {
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            
            .header {
                padding: 25px 20px;
            }
            
            .stats-grid {
                padding: 20px;
                gap: 12px;
            }
            
            .toolbar {
                padding: 20px;
                flex-direction: column;
            }
            
            .filters {
                width: 100%;
            }
            
            .filter-group {
                flex: 1;
                min-width: 150px;
            }
            
            .table-container {
                padding: 0 20px 20px;
            }
            
            th, td {
                padding: 12px 10px;
                font-size: 0.8rem;
            }
            
            .action-btns {
                flex-direction: column;
            }
        }

        @media (max-width: 640px) {
            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>

<?php include '../config/header.php'; ?>

<div class="container">
    <div class="glass-card">
        <!-- Header -->
        <div class="header">
            <h1>
                <i class="fas fa-chart-line"></i> 
                BBU Management
            </h1>
            <p style="margin-top: 10px; opacity: 0.7;">
                Track and manage all Budget Update entries
            </p>
        </div>

        <!-- Statistics Cards -->
        <div class="stats-grid">
            <div class="stat-card" onclick="filterByStatus('')">
                <div class="stat-icon">
                    <i class="fas fa-file-alt"></i>
                </div>
                <div class="stat-value"><?= number_format($stats['total'] ?? 0) ?></div>
                <div class="stat-label">Total BBU</div>
                <div class="stat-sub">All entries</div>
            </div>
            <div class="stat-card" onclick="filterByStatus('Draft')">
                <div class="stat-icon">
                    <i class="fas fa-edit"></i>
                </div>
                <div class="stat-value"><?= number_format($stats['draft'] ?? 0) ?></div>
                <div class="stat-label">Draft</div>
                <div class="stat-sub">₹ <?= number_format($stats['draft_value'] ?? 0, 2) ?></div>
            </div>
            <div class="stat-card" onclick="filterByStatus('Submitted')">
                <div class="stat-icon">
                    <i class="fas fa-paper-plane"></i>
                </div>
                <div class="stat-value"><?= number_format($stats['submitted'] ?? 0) ?></div>
                <div class="stat-label">Submitted</div>
                <div class="stat-sub">Pending approval</div>
            </div>
            <div class="stat-card" onclick="filterByStatus('Approved')">
                <div class="stat-icon">
                    <i class="fas fa-check-circle"></i>
                </div>
                <div class="stat-value"><?= number_format($stats['approved'] ?? 0) ?></div>
                <div class="stat-label">Approved</div>
                <div class="stat-sub">₹ <?= number_format($stats['approved_value'] ?? 0, 2) ?></div>
            </div>
            <div class="stat-card" onclick="filterByStatus('Rejected')">
                <div class="stat-icon">
                    <i class="fas fa-times-circle"></i>
                </div>
                <div class="stat-value"><?= number_format($stats['rejected'] ?? 0) ?></div>
                <div class="stat-label">Rejected</div>
                <div class="stat-sub">Returned</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-rupee-sign"></i>
                </div>
                <div class="stat-value">₹ <?= number_format($stats['total_value'] ?? 0, 0) ?></div>
                <div class="stat-label">Total Value</div>
                <div class="stat-sub">All BBUs combined</div>
            </div>
        </div>

        <!-- Toolbar -->
        <div class="toolbar">
            <form method="get" action="" id="filterForm" style="width: 100%; display: flex; flex-wrap: wrap; gap: 15px; justify-content: space-between;">
                <div class="filters">
                    <div class="filter-group">
                        <input type="text" name="search" placeholder="Search BBU No, BOQ Code, Description..." 
                               value="<?= htmlspecialchars($search) ?>" autocomplete="off">
                    </div>
                    <div class="filter-group">
                        <select name="status">
                            <option value="">All Status</option>
                            <option value="Draft" <?= $status == 'Draft' ? 'selected' : '' ?>>Draft</option>
                            <option value="Submitted" <?= $status == 'Submitted' ? 'selected' : '' ?>>Submitted</option>
                            <option value="Approved" <?= $status == 'Approved' ? 'selected' : '' ?>>Approved</option>
                            <option value="Rejected" <?= $status == 'Rejected' ? 'selected' : '' ?>>Rejected</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <select name="project_id">
                            <option value="">All Projects</option>
                            <?php 
                            $projects->data_seek(0);
                            while ($p = $projects->fetch_assoc()): ?>
                                <option value="<?= $p['id'] ?>" <?= $project_id == $p['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($p['project_code']) ?> - <?= htmlspecialchars($p['project_name']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <!-- <div class="filter-group">
                        <select name="rate_type">
                            <option value="">All Rate Types</option>
                            <option value="SITC" <?= $rate_type == 'SITC' ? 'selected' : '' ?>>SITC</option>
                            <option value="S+ITC" <?= $rate_type == 'S+ITC' ? 'selected' : '' ?>>S+ITC</option>
                        </select>
                    </div> -->
                    <div class="filter-group">
                        <input type="date" name="from_date" value="<?= $from_date ?>" placeholder="From Date">
                    </div>
                    <div class="filter-group">
                        <input type="date" name="to_date" value="<?= $to_date ?>" placeholder="To Date">
                    </div>
                </div>
                <div style="display: flex; gap: 10px;height: max-content;">
                    <!-- <button type="button" onclick="exportData('excel')" class="btn-export">
                        <i class="fas fa-file-excel"></i> Excel
                    </button>
                    <button type="button" onclick="exportData('pdf')" class="btn-export">
                        <i class="fas fa-file-pdf"></i> PDF
                    </button> -->
                    <a href="?reset=1" class="btn-reset">
                        <i class="fas fa-undo"></i> Reset
                    </a>
                    <a href="add_bbu.php" class="btn-add">
                        <i class="fas fa-plus"></i> New BBU
                    </a>
                </div>
            </form>
        </div>

        <!-- Table -->
        <div class="table-container">
            <?php if ($bbu_list->num_rows > 0): ?>
                <table id="bbuTable">
                    <thead>
                        <tr>
                            <th onclick="sortTable('bbu_no')">BBU No <i class="fas fa-sort"></i></th>
                            <th onclick="sortTable('project_code')">Project <i class="fas fa-sort"></i></th>
                            <th>Description</th>
                            <th onclick="sortTable('quantity')">Qty <i class="fas fa-sort"></i></th>
                            <th>Rate Type</th>
                            <th onclick="sortTable('total_amount')">Total Amount <i class="fas fa-sort"></i></th>
                            <th>Items</th>
                            <th onclick="sortTable('status')">Status <i class="fas fa-sort"></i></th>
                            <th onclick="sortTable('created_at')">Created <i class="fas fa-sort"></i></th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row = $bbu_list->fetch_assoc()): ?>
                            <tr>
                                <td>
                                    <strong><?= htmlspecialchars($row['bbu_no']) ?></strong>
                                    <?php if (!empty($row['boq_code'])): ?>
                                        <br><small style="color: #9ca3af;"><?= htmlspecialchars($row['boq_code']) ?></small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?= htmlspecialchars($row['project_code'] ?? 'N/A') ?>
                                    <br><small style="color: #9ca3af;"><?= htmlspecialchars(substr($row['project_name'] ?? '', 0, 30)) ?></small>
                                </td>
                                <td title="<?= htmlspecialchars($row['system_description']) ?>">
                                    <?= htmlspecialchars(substr($row['system_description'], 0, 50)) ?>
                                    <?php if (strlen($row['system_description']) > 50): ?>...<?php endif; ?>
                                </td>
                                <td><?= number_format($row['quantity'], 2) ?></td>
                                <td>
                                    <span class="rate-badge rate-<?= $row['rate_type'] == 'SITC' ? 'SITC' : 'SITC-plus' ?>">
                                        <?= htmlspecialchars($row['rate_type']) ?>
                                    </span>
                                </td>
                                <td>
                                    <strong>₹ <?= number_format($row['total_amount'] ?? 0, 2) ?></strong>
                                </td>
                                <td>
                                    <span style="background: rgba(139, 92, 246, 0.2); padding: 4px 10px; border-radius: 12px; font-size: 0.75rem;">
                                        <i class="fas fa-box"></i> <?= $row['items_count'] ?>
                                    </span>
                                </td>
                                <td>
    <span class="status-badge <?= getStatusBadgeClass($row['status']) ?>">
        <i class="fas <?= getStatusIcon($row['status']) ?>"></i>
        <?= $row['status'] ?>
    </span>

    <?php if ($row['status'] == 'Draft'): ?>
        <a href="update_status.php?id=<?= $row['id'] ?>&status=Submitted" 
           class="action-btn btn-view">Submit</a>
    <?php elseif ($row['status'] == 'Submitted'): ?>
        <a href="update_status.php?id=<?= $row['id'] ?>&status=Approved" 
           class="action-btn btn-edit">Approve</a>

        <a href="update_status.php?id=<?= $row['id'] ?>&status=Rejected" 
           class="action-btn btn-delete">Reject</a>
    <?php endif; ?>
</td>
                                <td>
                                    <small><?= date('d-m-Y', strtotime($row['created_at'])) ?></small>
                                    <br><small style="color: #9ca3af;"><?= htmlspecialchars($row['created_by_name'] ?? '') ?></small>
                                </td>
                                <td class="action-btns">
                                    <a href="view_bbu.php?id=<?= $row['id'] ?>" class="action-btn btn-view" title="View">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <?php if ($row['status'] == 'Draft'):?>
                                        <a href="edit_bbu.php?id=<?= $row['id'] ?>" class="action-btn btn-edit" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                    <?php endif; ?>    
                                    <?php if (($row['status'] == 'Draft')||($row['status'] == 'Rejected')) :?>    
                                        <a href="delete_bbu.php?id=<?= $row['id'] ?>" class="action-btn btn-delete" 
                                           onclick="return confirm('Are you sure you want to delete this BBU?')" title="Delete">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                        
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                            <a href="?page=1&search=<?= urlencode($search) ?>&status=<?= urlencode($status) ?>&project_id=<?= urlencode($project_id) ?>&rate_type=<?= urlencode($rate_type) ?>&from_date=<?= urlencode($from_date) ?>&to_date=<?= urlencode($to_date) ?>&sort_by=<?= urlencode($sort_by) ?>&sort_order=<?= urlencode($sort_order) ?>">
                                <i class="fas fa-angle-double-left"></i>
                            </a>
                            <a href="?page=<?= $page - 1 ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status) ?>&project_id=<?= urlencode($project_id) ?>&rate_type=<?= urlencode($rate_type) ?>&from_date=<?= urlencode($from_date) ?>&to_date=<?= urlencode($to_date) ?>&sort_by=<?= urlencode($sort_by) ?>&sort_order=<?= urlencode($sort_order) ?>">
                                <i class="fas fa-angle-left"></i>
                            </a>
                        <?php else: ?>
                            <span class="disabled"><i class="fas fa-angle-double-left"></i></span>
                            <span class="disabled"><i class="fas fa-angle-left"></i></span>
                        <?php endif; ?>

                        <?php
                        $start_page = max(1, $page - 2);
                        $end_page = min($total_pages, $page + 2);
                        for ($i = $start_page; $i <= $end_page; $i++):
                        ?>
                            <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status) ?>&project_id=<?= urlencode($project_id) ?>&rate_type=<?= urlencode($rate_type) ?>&from_date=<?= urlencode($from_date) ?>&to_date=<?= urlencode($to_date) ?>&sort_by=<?= urlencode($sort_by) ?>&sort_order=<?= urlencode($sort_order) ?>" 
                               class="<?= $i == $page ? 'active' : '' ?>">
                                <?= $i ?>
                            </a>
                        <?php endfor; ?>

                        <?php if ($page < $total_pages): ?>
                            <a href="?page=<?= $page + 1 ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status) ?>&project_id=<?= urlencode($project_id) ?>&rate_type=<?= urlencode($rate_type) ?>&from_date=<?= urlencode($from_date) ?>&to_date=<?= urlencode($to_date) ?>&sort_by=<?= urlencode($sort_by) ?>&sort_order=<?= urlencode($sort_order) ?>">
                                <i class="fas fa-angle-right"></i>
                            </a>
                            <a href="?page=<?= $total_pages ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status) ?>&project_id=<?= urlencode($project_id) ?>&rate_type=<?= urlencode($rate_type) ?>&from_date=<?= urlencode($from_date) ?>&to_date=<?= urlencode($to_date) ?>&sort_by=<?= urlencode($sort_by) ?>&sort_order=<?= urlencode($sort_order) ?>">
                                <i class="fas fa-angle-double-right"></i>
                            </a>
                        <?php else: ?>
                            <span class="disabled"><i class="fas fa-angle-right"></i></span>
                            <span class="disabled"><i class="fas fa-angle-double-right"></i></span>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
                
                <!-- Info -->
                <div style="margin-top: 20px; text-align: center; font-size: 0.8rem; color: #9ca3af;">
                    Showing <?= ($offset + 1) ?> to <?= min($offset + $limit, $total_records) ?> of <?= $total_records ?> entries
                </div>
            <?php else: ?>
                <div class="empty-state">
                    <i class="fas fa-inbox"></i>
                    <h3>No BBU Records Found</h3>
                    <p style="margin-bottom: 20px;">Create your first BBU entry to get started.</p>
                    <a href="add_bbu.php" class="btn-add">
                        <i class="fas fa-plus"></i> Create New BBU
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div id="deleteModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <i class="fas fa-exclamation-triangle" style="color: #f87171;"></i>
            Confirm Delete
        </div>
        <div class="modal-body">
            Are you sure you want to delete BBU: <strong id="deleteBbuNo"></strong>?
            <p style="margin-top: 10px; color: #fca5a5; font-size: 0.9rem;">
                <i class="fas fa-info-circle"></i> This action cannot be undone and will restore the issued materials back to inventory.
            </p>
        </div>
        <div class="modal-footer">
            <button class="modal-btn modal-btn-cancel" onclick="closeModal()">Cancel</button>
            <button class="modal-btn modal-btn-confirm" onclick="confirmDelete()">Delete</button>
        </div>
    </div>
</div>

<!-- Toast Notification -->
<div id="toast" class="toast">
    <i class="fas fa-check-circle"></i>
    <span id="toastMessage"></span>
</div>

<script>
let deleteId = null;
let currentUrl = new URL(window.location.href);

// Delete BBU function
function deleteBBU(id, bbuNo) {
    deleteId = id;
    document.getElementById('deleteBbuNo').innerText = bbuNo;
    document.getElementById('deleteModal').style.display = 'flex';
}

// Close modal
function closeModal() {
    document.getElementById('deleteModal').style.display = 'none';
    deleteId = null;
}

// Confirm delete
function confirmDelete() {
    if (deleteId) {
        window.location.href = `delete_bbu.php?id=${deleteId}`;
    }
}

// Close modal when clicking outside
window.onclick = function(event) {
    const modal = document.getElementById('deleteModal');
    if (event.target === modal) {
        closeModal();
    }
}

// Auto-submit form on filter change
document.querySelectorAll('.filter-group select, .filter-group input[type="date"]').forEach(element => {
    element.addEventListener('change', function() {
        document.getElementById('filterForm').submit();
    });
});

// Debounce search input
let debounceTimer;
document.querySelector('input[name="search"]')?.addEventListener('input', function() {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
        document.getElementById('filterForm').submit();
    }, 500);
});

// Sort table
function sortTable(column) {
    let currentSortBy = '<?= $sort_by ?>';
    let currentSortOrder = '<?= $sort_order ?>';
    
    let newSortOrder = 'ASC';
    if (currentSortBy === column && currentSortOrder === 'ASC') {
        newSortOrder = 'DESC';
    }
    
    const url = new URL(window.location.href);
    url.searchParams.set('sort_by', column);
    url.searchParams.set('sort_order', newSortOrder);
    url.searchParams.set('page', '1');
    window.location.href = url.toString();
}

// Filter by status from stats card
function filterByStatus(status) {
    const url = new URL(window.location.href);
    if (status) {
        url.searchParams.set('status', status);
    } else {
        url.searchParams.delete('status');
    }
    url.searchParams.set('page', '1');
    window.location.href = url.toString();
}

// Export data
function exportData(type) {
    const url = new URL(window.location.href);
    url.searchParams.set('export', type);
    window.location.href = url.toString();
}

// Show toast message
function showToast(message, isError = false) {
    const toast = document.getElementById('toast');
    const toastMessage = document.getElementById('toastMessage');
    toastMessage.innerText = message;
    
    if (isError) {
        toast.style.background = 'rgba(239, 68, 68, 0.9)';
    } else {
        toast.style.background = 'rgba(34, 197, 94, 0.9)';
    }
    
    toast.style.display = 'flex';
    setTimeout(() => {
        toast.style.display = 'none';
    }, 3000);
}

// Check for success/error messages from URL parameters
document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const success = urlParams.get('success');
    const error = urlParams.get('error');
    
    if (success) {
        showToast(success);
        // Remove from URL without refreshing
        const newUrl = window.location.pathname;
        window.history.pushState({}, '', newUrl);
    }
    
    if (error) {
        showToast(error, true);
        window.history.pushState({}, '', window.location.pathname);
    }
});
</script>

</body>
</html>

<?php $conn->close(); ?>