<?php
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();
}

$bbu_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($bbu_id == 0) {
    header("Location: bbu_list.php");
    exit();
}

// Fetch BBU data with all details
$bbu_query = $conn->prepare("
    SELECT 
        b.*,
        p.project_code,
        p.project_name,
        p.project_address as project_location,
        u.full_name as created_by_name,
        u2.full_name as updated_by_name,
        uom.uom_name
    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
    LEFT JOIN users u2 ON b.updated_by = u2.id
    LEFT JOIN uom_tbl uom ON b.uom_id = uom.id
    WHERE b.id = ?
");
$bbu_query->bind_param("i", $bbu_id);
$bbu_query->execute();
$bbu_data = $bbu_query->get_result()->fetch_assoc();

if (!$bbu_data) {
    $_SESSION['error'] = "BBU not found.";
    header("Location: bbu_list.php");
    exit();
}

// Fetch BBU items
$items_query = $conn->prepare("
    SELECT 
        bi.*
        
    FROM bbu_items bi
    
    WHERE bi.bbu_id = ?
    ORDER BY bi.id
");
$items_query->bind_param("i", $bbu_id);
$items_query->execute();
$bbu_items = $items_query->get_result()->fetch_all(MYSQLI_ASSOC);

// Calculate totals
$total_quantity = array_sum(array_column($bbu_items, 'quantity'));
$total_amount = array_sum(array_column($bbu_items, 'amount'));

// 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>View BBU | <?= htmlspecialchars($bbu_data['bbu_no']) ?></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: 1400px;
            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;
            position: relative;
            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;
        }

        .back-link {
            position: absolute;
            left: 35px;
            top: 40px;
            color: #a78bfa;
            text-decoration: none;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }

        .back-link:hover {
            color: #c4b5fd;
            transform: translateX(-5px);
        }

        .action-buttons {
            position: absolute;
            right: 35px;
            top: 40px;
            display: flex;
            gap: 12px;
        }

        .btn-action {
            padding: 10px 20px;
            border-radius: 40px;
            text-decoration: none;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
            font-size: 0.9rem;
        }

        .btn-edit {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            color: white;
        }

        .btn-edit:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(245, 158, 11, 0.3);
        }

        .btn-print {
            background: linear-gradient(135deg, #6b7280, #4b5563);
            color: white;
        }

        .btn-print:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(107, 114, 128, 0.3);
        }

        .content {
            padding: 40px;
        }

        /* Status Badge */
        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            border-radius: 40px;
            font-size: 0.85rem;
            font-weight: 600;
        }

        .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;
        }

        /* Info Cards */
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .info-card {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 20px;
            padding: 20px;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .info-label {
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: #9ca3af;
            margin-bottom: 8px;
        }

        .info-value {
            font-size: 1.1rem;
            font-weight: 600;
            color: #f1f5f9;
        }

        .info-value-large {
            font-size: 1.5rem;
            font-weight: 700;
            color: #c4b5fd;
        }

        /* Section Titles */
        .section-title {
            font-size: 1.3rem;
            font-weight: 600;
            margin: 30px 0 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            color: #c4b5fd;
            padding-bottom: 10px;
            border-bottom: 2px solid rgba(139, 92, 246, 0.3);
        }

        /* BOQ Section */
        .boq-details {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 20px;
            padding: 25px;
            margin-bottom: 30px;
        }

        .boq-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
        }

        /* Items Table */
        .table-container {
            overflow-x: auto;
            margin-top: 20px;
        }

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

        th {
            text-align: left;
            padding: 15px;
            background: rgba(139, 92, 246, 0.2);
            font-weight: 600;
            font-size: 0.85rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

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

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

        /* Summary Cards */
        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }

        .summary-card {
            background: linear-gradient(135deg, rgba(139, 92, 246, 0.2), rgba(59, 130, 246, 0.1));
            border-radius: 16px;
            padding: 20px;
            text-align: center;
        }

        .summary-label {
            font-size: 0.8rem;
            color: #9ca3af;
            margin-bottom: 8px;
        }

        .summary-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #c4b5fd;
        }

        /* Print Styles */
        @media print {
            body {
                background: white;
                padding: 0;
                margin: 0;
            }
            
            .glass-card {
                background: white;
                backdrop-filter: none;
                box-shadow: none;
                border: 1px solid #ddd;
            }
            
            .header {
                background: #f3f4f6;
                color: #000;
            }
            
            .header h1 {
                background: none;
                color: #000;
                -webkit-text-fill-color: #000;
            }
            
            .back-link, .action-buttons, .btn-action, .btn-edit, .btn-print {
                display: none !important;
            }
            
            .status-badge {
                border: 1px solid #000;
            }
            
            .info-card, .boq-details, .summary-card {
                background: #f9fafb;
                border: 1px solid #e5e7eb;
                color: #000;
            }
            
            .info-value, .info-value-large, .summary-value, .section-title {
                color: #000;
            }
            
            th {
                background: #e5e7eb;
                color: #000;
            }
            
            td {
                border-bottom: 1px solid #e5e7eb;
                color: #000;
            }
            
            .glass-card {
                border: none;
            }
        }

        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            
            .header {
                padding: 30px 20px;
            }
            
            .back-link, .action-buttons {
                position: static;
                margin-bottom: 15px;
            }
            
            .action-buttons {
                margin-top: 15px;
                justify-content: center;
            }
            
            .content {
                padding: 20px;
            }
            
            .info-grid {
                grid-template-columns: 1fr;
            }
            
            th, td {
                padding: 10px;
                font-size: 0.8rem;
            }
        }
    </style>
</head>
<body>

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

<div class="container">
    <div class="glass-card">
        <div class="header">
            <a href="bbu_list.php" class="back-link">
                <i class="fas fa-arrow-left"></i> Back to BBU List
            </a>
            <h1 style="margin-top: 10px;">
                <i class="fas fa-file-alt"></i> 
                BBU Details
            </h1>
            <div class="action-buttons">
                <?php if ($bbu_data['status'] == 'Draft'): ?>
                    <a href="edit_bbu.php?id=<?= $bbu_id ?>" class="btn-action btn-edit">
                        <i class="fas fa-edit"></i> Edit
                    </a>
                <?php endif; ?>
                <a  href="print_bbu.php?id=<?= $bbu_id ?>" class="btn-action btn-print">
                    <i class="fas fa-print"></i> Print
                </a>
            </div>
        </div>

        <div class="content">
            <!-- Status Banner -->
            <div style="margin-bottom: 25px;">
                <span class="status-badge <?= getStatusBadgeClass($bbu_data['status']) ?>">
                    <i class="fas <?= getStatusIcon($bbu_data['status']) ?>"></i>
                    Status: <?= $bbu_data['status'] ?>
                </span>
            </div>

            <!-- Basic Information -->
            <div class="info-grid">
                <div class="info-card">
                    <div class="info-label">
                        <i class="fas fa-hashtag"></i> BBU Number
                    </div>
                    <div class="info-value-large"><?= htmlspecialchars($bbu_data['bbu_no']) ?></div>
                </div>
                <div class="info-card">
                    <div class="info-label">
                        <i class="fas fa-calendar"></i> Created Date
                    </div>
                    <div class="info-value"><?= date('d-m-Y h:i A', strtotime($bbu_data['created_at'])) ?></div>
                </div>
                <div class="info-card">
                    <div class="info-label">
                        <i class="fas fa-user"></i> Created By
                    </div>
                    <div class="info-value"><?= htmlspecialchars($bbu_data['created_by_name'] ?? 'System') ?></div>
                </div>
                <?php if ($bbu_data['updated_at'] && $bbu_data['updated_at'] != $bbu_data['created_at']): ?>
                <div class="info-card">
                    <div class="info-label">
                        <i class="fas fa-clock"></i> Last Updated
                    </div>
                    <div class="info-value"><?= date('d-m-Y h:i A', strtotime($bbu_data['updated_at'])) ?></div>
                </div>
                <div class="info-card">
                    <div class="info-label">
                        <i class="fas fa-user-edit"></i> Updated By
                    </div>
                    <div class="info-value"><?= htmlspecialchars($bbu_data['updated_by_name'] ?? '-') ?></div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Project Details -->
            <div class="section-title">
                <i class="fas fa-building"></i>
                <span>Project Information</span>
            </div>
            <div class="info-grid">
                <div class="info-card">
                    <div class="info-label">Project Code</div>
                    <div class="info-value"><?= htmlspecialchars($bbu_data['project_code'] ?? 'N/A') ?></div>
                </div>
                <div class="info-card">
                    <div class="info-label">Project Name</div>
                    <div class="info-value"><?= htmlspecialchars($bbu_data['project_name'] ?? 'N/A') ?></div>
                </div>
                <div class="info-card">
                    <div class="info-label">BOQ Code</div>
                    <div class="info-value"><?= htmlspecialchars($bbu_data['boq_code'] ?? 'N/A') ?></div>
                </div>
            </div>

            <!-- BOQ Details -->
            <div class="section-title">
                <i class="fas fa-file-invoice"></i>
                <span>Bill of Quantity (BOQ) Details</span>
            </div>
            <div class="boq-details">
                <div class="boq-grid">
                    <div>
                        <div class="info-label">System Description</div>
                        <div class="info-value"><?= nl2br(htmlspecialchars($bbu_data['system_description'])) ?></div>
                    </div>
                    <div>
                        <div class="info-label">UOM</div>
                        <div class="info-value"><?= htmlspecialchars($bbu_data['uom_name'] ?? 'N/A') ?></div>
                    </div>
                    <div>
                        <div class="info-label">Total Quantity</div>
                        <div class="info-value"><?= number_format($bbu_data['quantity'], 3) ?></div>
                    </div>
                    <div>
                        <div class="info-label">Rate Type</div>
                        <div class="info-value">
                            <span class="rate-badge rate-<?= $bbu_data['rate_type'] == 'SITC' ? 'sitc' : 'sitc-plus' ?>">
                                <?= htmlspecialchars($bbu_data['rate_type']) ?>
                            </span>
                        </div>
                    </div>
                    
                    <?php if ($bbu_data['rate_type'] == 'SITC'): ?>
                    <div>
                        <div class="info-label">SITC Rate</div>
                        <div class="info-value">₹ <?= number_format($bbu_data['sitc_rate'] ?? 0, 2) ?></div>
                    </div>
                    <div>
                        <div class="info-label">SITC Amount</div>
                        <div class="info-value">₹ <?= number_format($bbu_data['sitc_amount'] ?? 0, 2) ?></div>
                    </div>
                    <?php else: ?>
                    <div>
                        <div class="info-label">Supply Rate</div>
                        <div class="info-value">₹ <?= number_format($bbu_data['supply_rate'] ?? 0, 2) ?></div>
                    </div>
                    <div>
                        <div class="info-label">ITC Rate</div>
                        <div class="info-value">₹ <?= number_format($bbu_data['itc_rate'] ?? 0, 2) ?></div>
                    </div>
                    <div>
                        <div class="info-label">Supply Amount</div>
                        <div class="info-value">₹ <?= number_format($bbu_data['supply_amount'] ?? 0, 2) ?></div>
                    </div>
                    <div>
                        <div class="info-label">ITC Amount</div>
                        <div class="info-value">₹ <?= number_format($bbu_data['itc_amount'] ?? 0, 2) ?></div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <?php if (!empty($bbu_data['boq_remarks'])): ?>
                <div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid rgba(255,255,255,0.1);">
                    <div class="info-label">BOQ Remarks</div>
                    <div class="info-value"><?= nl2br(htmlspecialchars($bbu_data['boq_remarks'])) ?></div>
                </div>
                <?php endif; ?>
            </div>

            <!-- BBU Items -->
            <div class="section-title">
                <i class="fas fa-list"></i>
                <span>Issued Materials</span>
            </div>
            
            <?php if (empty($bbu_items)): ?>
                <div style="text-align: center; padding: 60px 20px; background: rgba(255,255,255,0.03); border-radius: 20px;">
                    <i class="fas fa-box-open" style="font-size: 3rem; opacity: 0.3; margin-bottom: 15px;"></i>
                    <p>No items found in this BBU.</p>
                </div>
            <?php else: ?>
                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>RA No</th>
                                <th>Model No</th>
                                <th>Item Name</th>
                                <th>Category</th>
                                <th>Serial No</th>
                                <th>Quantity</th>
                                <th>Rate (₹)</th>
                                <th>Amount (₹)</th>
                                <th>Remarks</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($bbu_items as $item): ?>
                            <tr>
                                <td><?= $item['sr_no'] ?></td>
                                <td><strong><?= htmlspecialchars($item['ra_no']) ?></strong></td>
                                <td><?= htmlspecialchars($item['model_no'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($item['item_name'] ?? '-') ?></td>
                                <td>
                                    <?php if (!empty($item['category'])): ?>
                                        <span style="background: rgba(139, 92, 246, 0.2); padding: 4px 10px; border-radius: 12px; font-size: 0.75rem;">
                                            <?= htmlspecialchars($item['category']) ?>
                                        </span>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if (!empty($item['serial_no'])): ?>
                                        <span style="font-family: monospace; background: rgba(0,0,0,0.3); padding: 4px 8px; border-radius: 6px;">
                                            <?= htmlspecialchars($item['serial_no']) ?>
                                        </span>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                                <td><?= number_format($item['quantity'], 3) ?></td>
                                <td>₹ <?= number_format($item['rate'], 2) ?></td>
                                <td><strong>₹ <?= number_format($item['amount'], 2) ?></strong></td>
                                <td><?= htmlspecialchars($item['remarks'] ?? '-') ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Summary -->
                <div class="summary-grid">
                    <div class="summary-card">
                        <div class="summary-label">Total Items</div>
                        <div class="summary-value"><?= count($bbu_items) ?></div>
                    </div>
                    <div class="summary-card">
                        <div class="summary-label">Total Quantity</div>
                        <div class="summary-value"><?= number_format($total_quantity, 3) ?></div>
                    </div>
                    <div class="summary-card">
                        <div class="summary-label">Total Amount</div>
                        <div class="summary-value">₹ <?= number_format($total_amount, 2) ?></div>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Overall Remarks -->
            <?php if (!empty($bbu_data['remarks'])): ?>
            <div class="section-title">
                <i class="fas fa-comment"></i>
                <span>Additional Remarks</span>
            </div>
            <div class="boq-details">
                <div class="info-value"><?= nl2br(htmlspecialchars($bbu_data['remarks'])) ?></div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
.rate-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.75rem;
    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;
}
</style>

</body>
</html>

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