<?php
/**
 * print_bbu.php - Professional Print View for BBU
 * Optimized for printing with multiple format 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();
}

$bbu_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$format = isset($_GET['format']) ? $_GET['format'] : 'default'; // default, compact, detailed

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,
        p.start_date as project_start_date,
        p.end_date as project_end_date,
        u.full_name as created_by_name,
        u2.full_name as updated_by_name,
        uom.uom_name,
        CASE 
            WHEN b.rate_type = 'SITC' THEN b.sitc_amount
            ELSE (b.supply_amount + b.itc_amount)
        END as total_amount
    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 company info from config or settings
$company_name = "Your Company Name";
$company_address = "123 Business Street, City, State - 123456";
$company_phone = "+91 1234567890";
$company_email = "info@company.com";
$company_gst = "GSTIN: 123456789012345";

function getStatusText($status) {
    switch ($status) {
        case 'Draft': return 'DRAFT';
        case 'Submitted': return 'SUBMITTED';
        case 'Approved': return 'APPROVED';
        case 'Rejected': return 'REJECTED';
        default: return strtoupper($status);
    }
}

function numberToWords($number) {
    $words = array(
        '0' => '', '1' => 'One', '2' => 'Two', '3' => 'Three', '4' => 'Four', 
        '5' => 'Five', '6' => 'Six', '7' => 'Seven', '8' => 'Eight', '9' => 'Nine',
        '10' => 'Ten', '11' => 'Eleven', '12' => 'Twelve', '13' => 'Thirteen', 
        '14' => 'Fourteen', '15' => 'Fifteen', '16' => 'Sixteen', '17' => 'Seventeen', 
        '18' => 'Eighteen', '19' => 'Nineteen', '20' => 'Twenty', '30' => 'Thirty', 
        '40' => 'Forty', '50' => 'Fifty', '60' => 'Sixty', '70' => 'Seventy', 
        '80' => 'Eighty', '90' => 'Ninety'
    );
    
    if ($number == 0) return 'Zero';
    
    $amount = number_format($number, 2, '.', '');
    $parts = explode('.', $amount);
    $rupees = (int)$parts[0];
    $paise = isset($parts[1]) ? (int)$parts[1] : 0;
    
    $rupees_words = '';
    if ($rupees >= 10000000) {
        $crores = floor($rupees / 10000000);
        $rupees_words .= $words[$crores] . ' Crore ';
        $rupees %= 10000000;
    }
    if ($rupees >= 100000) {
        $lakhs = floor($rupees / 100000);
        $rupees_words .= $words[$lakhs] . ' Lakh ';
        $rupees %= 100000;
    }
    if ($rupees >= 1000) {
        $thousands = floor($rupees / 1000);
        $rupees_words .= $words[$thousands] . ' Thousand ';
        $rupees %= 1000;
    }
    if ($rupees >= 100) {
        $hundreds = floor($rupees / 100);
        $rupees_words .= $words[$hundreds] . ' Hundred ';
        $rupees %= 100;
    }
    if ($rupees > 0) {
        if ($rupees <= 20) {
            $rupees_words .= $words[$rupees] . ' ';
        } else {
            $tens = floor($rupees / 10) * 10;
            $ones = $rupees % 10;
            $rupees_words .= $words[$tens] . ' ' . $words[$ones] . ' ';
        }
    }
    
    $result = trim($rupees_words) . ' Rupees';
    if ($paise > 0) {
        $result .= ' and ' . $words[$paise] . ' Paise';
    }
    $result .= ' Only';
    
    return $result;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BBU Print - <?= 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">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', 'Inter', system-ui, -apple-system, sans-serif;
            background: #e5e7eb;
            padding: 20px;
        }

        /* Print Container */
        .print-container {
            max-width: 1200px;
            margin: 0 auto;
        }

        /* Print Controls */
        .print-controls {
            background: white;
            border-radius: 12px;
            padding: 15px 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }

        .print-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: #1f2937;
        }

        .btn-group {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

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

        .btn-primary {
            background: #3b82f6;
            color: white;
        }

        .btn-primary:hover {
            background: #2563eb;
            transform: translateY(-1px);
        }

        .btn-secondary {
            background: #6b7280;
            color: white;
        }

        .btn-secondary:hover {
            background: #4b5563;
        }

        .btn-success {
            background: #10b981;
            color: white;
        }

        .btn-success:hover {
            background: #059669;
        }

        /* Print Document */
        .print-document {
            background: white;
            border-radius: 12px;
            padding: 40px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
            position: relative;
        }

        /* Company Header */
        .company-header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #e5e7eb;
        }

        .company-name {
            font-size: 24px;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 8px;
        }

        .company-details {
            font-size: 12px;
            color: #6b7280;
            line-height: 1.5;
        }

        /* Document Title */
        .document-title {
            text-align: center;
            margin: 30px 0;
        }

        .document-title h2 {
            font-size: 20px;
            font-weight: 700;
            color: #1f2937;
            text-transform: uppercase;
            letter-spacing: 2px;
        }

        .document-title .bbu-number {
            font-size: 16px;
            color: #6b7280;
            margin-top: 5px;
        }

        /* Status Badge Print */
        .status-badge-print {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .status-draft { background: #fef3c7; color: #d97706; border: 1px solid #fbbf24; }
        .status-submitted { background: #dbeafe; color: #2563eb; border: 1px solid #60a5fa; }
        .status-approved { background: #d1fae5; color: #059669; border: 1px solid #34d399; }
        .status-rejected { background: #fee2e2; color: #dc2626; border: 1px solid #f87171; }

        /* Info Grid */
        .info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            margin-bottom: 30px;
        }

        .info-section {
            background: #f9fafb;
            padding: 15px;
            border-radius: 8px;
            border: 1px solid #e5e7eb;
        }

        .info-section-title {
            font-size: 14px;
            font-weight: 700;
            color: #374151;
            margin-bottom: 12px;
            padding-bottom: 8px;
            border-bottom: 2px solid #e5e7eb;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .info-row {
            display: flex;
            margin-bottom: 8px;
            font-size: 13px;
        }

        .info-label {
            width: 120px;
            font-weight: 600;
            color: #6b7280;
        }

        .info-value {
            flex: 1;
            color: #1f2937;
        }

        /* Items Table */
        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            font-size: 12px;
        }

        .items-table th {
            background: #f3f4f6;
            padding: 12px;
            text-align: left;
            font-weight: 700;
            color: #374151;
            border: 1px solid #e5e7eb;
        }

        .items-table td {
            padding: 10px;
            border: 1px solid #e5e7eb;
            color: #4b5563;
        }

        .items-table tbody tr:hover {
            background: #f9fafb;
        }

        /* Summary Section */
        .summary-section {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 2px solid #e5e7eb;
        }

        .summary-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }

        .summary-box {
            background: #f9fafb;
            padding: 15px;
            text-align: center;
            border-radius: 8px;
            border: 1px solid #e5e7eb;
        }

        .summary-label {
            font-size: 11px;
            color: #6b7280;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 5px;
        }

        .summary-value {
            font-size: 18px;
            font-weight: 700;
            color: #1f2937;
        }

        .amount-words {
            background: #fef3c7;
            padding: 12px;
            border-radius: 8px;
            margin-top: 15px;
            font-size: 12px;
            color: #92400e;
            border-left: 4px solid #f59e0b;
        }

        /* Signatures */
        .signatures {
            display: flex;
            justify-content: space-between;
            margin-top: 50px;
            padding-top: 30px;
        }

        .signature-line {
            text-align: center;
            width: 200px;
        }

        .signature-line .line {
            border-top: 1px solid #9ca3af;
            margin-bottom: 8px;
            width: 100%;
        }

        .signature-line .label {
            font-size: 11px;
            color: #6b7280;
        }

        /* Footer */
        .print-footer {
            margin-top: 30px;
            padding-top: 20px;
            text-align: center;
            font-size: 10px;
            color: #9ca3af;
            border-top: 1px solid #e5e7eb;
        }

        /* Print Styles */
        @media print {
            body {
                background: white;
                padding: 0;
                margin: 0;
            }
            
            .print-controls {
                display: none;
            }
            
            .print-document {
                padding: 20px;
                box-shadow: none;
                border-radius: 0;
            }
            
            .btn-group, .btn {
                display: none;
            }
            
            .items-table th {
                background: #f3f4f6 !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .status-badge-print {
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .summary-box, .info-section, .amount-words {
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
        }

        /* Compact Mode */
        .print-document.compact .info-grid {
            grid-template-columns: 1fr;
        }
        
        .print-document.compact .summary-grid {
            grid-template-columns: repeat(3, 1fr);
        }
        
        .print-document.compact .items-table th,
        .print-document.compact .items-table td {
            padding: 6px;
            font-size: 11px;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .print-controls {
                flex-direction: column;
                align-items: stretch;
            }
            
            .btn-group {
                justify-content: center;
            }
            
            .info-grid {
                grid-template-columns: 1fr;
            }
            
            .summary-grid {
                grid-template-columns: 1fr;
            }
            
            .signatures {
                flex-direction: column;
                gap: 30px;
                align-items: center;
            }
        }
    </style>
</head>
<body>

<div class="print-container">
    <!-- Print Controls -->
    <div class="print-controls">
        <div class="print-title">
            <i class="fas fa-print"></i> BBU Document Print
        </div>
        <div class="btn-group">
            <button onclick="window.print()" class="btn btn-primary">
                <i class="fas fa-print"></i> Print
            </button>
            <button onclick="downloadAsPDF()" class="btn btn-success">
                <i class="fas fa-file-pdf"></i> Download PDF
            </button>
            <a href="view_bbu.php?id=<?= $bbu_id ?>" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back
            </a>
        </div>
    </div>

    <!-- Print Document -->
    <div class="print-document <?= $format == 'compact' ? 'compact' : '' ?>" id="printDocument">
        
        <!-- Company Header -->
        <div class="company-header">
            <div class="company-name"><?= htmlspecialchars($company_name) ?></div>
            <div class="company-details">
                <?= htmlspecialchars($company_address) ?><br>
                Phone: <?= htmlspecialchars($company_phone) ?> | Email: <?= htmlspecialchars($company_email) ?><br>
                <?= htmlspecialchars($company_gst) ?>
            </div>
        </div>

        <!-- Document Title -->
        <div class="document-title">
            <h2>BBU (Budget Update)</h2>
            <div class="bbu-number">
                <strong><?= htmlspecialchars($bbu_data['bbu_no']) ?></strong>
                <span class="status-badge-print status-<?= strtolower($bbu_data['status']) ?>" style="margin-left: 10px;">
                    <?= getStatusText($bbu_data['status']) ?>
                </span>
            </div>
        </div>

        <!-- Basic Information -->
        <div class="info-grid">
            <div class="info-section">
                <div class="info-section-title">
                    <i class="fas fa-info-circle"></i> Basic Information
                </div>
                <div class="info-row">
                    <div class="info-label">BBU Number:</div>
                    <div class="info-value"><?= htmlspecialchars($bbu_data['bbu_no']) ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Created Date:</div>
                    <div class="info-value"><?= date('d-m-Y', strtotime($bbu_data['created_at'])) ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">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-row">
                    <div class="info-label">Last Updated:</div>
                    <div class="info-value"><?= date('d-m-Y', strtotime($bbu_data['updated_at'])) ?></div>
                </div>
                <?php endif; ?>
            </div>

            <div class="info-section">
                <div class="info-section-title">
                    <i class="fas fa-building"></i> Project Information
                </div>
                <div class="info-row">
                    <div class="info-label">Project Code:</div>
                    <div class="info-value"><?= htmlspecialchars($bbu_data['project_code'] ?? 'N/A') ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Project Name:</div>
                    <div class="info-value"><?= htmlspecialchars($bbu_data['project_name'] ?? 'N/A') ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Location:</div>
                    <div class="info-value"><?= htmlspecialchars($bbu_data['project_location'] ?? 'N/A') ?></div>
                </div>
                <?php if ($bbu_data['project_start_date']): ?>
                <div class="info-row">
                    <div class="info-label">Project Period:</div>
                    <div class="info-value">
                        <?= date('d-m-Y', strtotime($bbu_data['project_start_date'])) ?> - 
                        <?= date('d-m-Y', strtotime($bbu_data['project_end_date'])) ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- BOQ Details -->
        <div class="info-section" style="margin-bottom: 20px;">
            <div class="info-section-title">
                <i class="fas fa-file-invoice"></i> BOQ Details
            </div>
            <div class="info-row">
                <div class="info-label">BOQ Code:</div>
                <div class="info-value"><?= htmlspecialchars($bbu_data['boq_code'] ?? 'N/A') ?></div>
            </div>
            <div class="info-row">
                <div class="info-label">System Description:</div>
                <div class="info-value"><?= nl2br(htmlspecialchars($bbu_data['system_description'])) ?></div>
            </div>
            <div class="info-row">
                <div class="info-label">UOM:</div>
                <div class="info-value"><?= htmlspecialchars($bbu_data['uom_name'] ?? 'N/A') ?></div>
            </div>
            <div class="info-row">
                <div class="info-label">Total Quantity:</div>
                <div class="info-value"><?= number_format($bbu_data['quantity'], 3) ?></div>
            </div>
            <div class="info-row">
                <div class="info-label">Rate Type:</div>
                <div class="info-value"><?= htmlspecialchars($bbu_data['rate_type']) ?></div>
            </div>
            
            <?php if ($bbu_data['rate_type'] == 'SITC'): ?>
            <div class="info-row">
                <div class="info-label">SITC Rate:</div>
                <div class="info-value">₹ <?= number_format($bbu_data['sitc_rate'] ?? 0, 2) ?></div>
            </div>
            <div class="info-row">
                <div class="info-label">SITC Amount:</div>
                <div class="info-value">₹ <?= number_format($bbu_data['sitc_amount'] ?? 0, 2) ?></div>
            </div>
            <?php else: ?>
            <div class="info-row">
                <div class="info-label">Supply Rate:</div>
                <div class="info-value">₹ <?= number_format($bbu_data['supply_rate'] ?? 0, 2) ?></div>
            </div>
            <div class="info-row">
                <div class="info-label">ITC Rate:</div>
                <div class="info-value">₹ <?= number_format($bbu_data['itc_rate'] ?? 0, 2) ?></div>
            </div>
            <div class="info-row">
                <div class="info-label">Supply Amount:</div>
                <div class="info-value">₹ <?= number_format($bbu_data['supply_amount'] ?? 0, 2) ?></div>
            </div>
            <div class="info-row">
                <div class="info-label">ITC Amount:</div>
                <div class="info-value">₹ <?= number_format($bbu_data['itc_amount'] ?? 0, 2) ?></div>
            </div>
            <?php endif; ?>
            
            <?php if (!empty($bbu_data['boq_remarks'])): ?>
            <div class="info-row">
                <div class="info-label">BOQ Remarks:</div>
                <div class="info-value"><?= nl2br(htmlspecialchars($bbu_data['boq_remarks'])) ?></div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Items Table -->
        <div style="margin: 20px 0;">
            <div class="info-section-title">
                <i class="fas fa-list"></i> Issued Materials
            </div>
            
            <?php if (empty($bbu_items)): ?>
                <div style="text-align: center; padding: 40px; background: #f9fafb; border-radius: 8px;">
                    <p>No items found in this BBU.</p>
                </div>
            <?php else: ?>
                <table class="items-table">
                    <thead>
                        <tr>
                            <th width="5%">#</th>
                            <th width="10%">RA No</th>
                            <th width="15%">Model No</th>
                            <th width="20%">Item Name</th>
                            <th width="15%">Serial No</th>
                            <th width="10%">Quantity</th>
                            <th width="10%">Rate (₹)</th>
                            <th width="15%">Amount (₹)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($bbu_items as $item): ?>
                        <tr>
                            <td><?= $item['sr_no'] ?></td>
                            <td><?= htmlspecialchars($item['ra_no']) ?></td>
                            <td><?= htmlspecialchars($item['model_no'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($item['item_name'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($item['serial_no'] ?? '-') ?></td>
                            <td><?= number_format($item['quantity'], 3) ?> <?= htmlspecialchars($item['item_uom'] ?? '') ?></td>
                            <td>₹ <?= number_format($item['rate'], 2) ?></td>
                            <td><strong>₹ <?= number_format($item['amount'], 2) ?></strong></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr style="background: #f3f4f6; font-weight: 700;">
                            <td colspan="6"></td>
                            <td><strong>Total:</strong></td>
                            <td><strong>₹ <?= number_format($total_amount, 2) ?></strong></td>
                        </tr>
                    </tfoot>
                </table>
            <?php endif; ?>
        </div>

        <!-- Summary -->
        <div class="summary-section">
            <div class="summary-grid">
                <div class="summary-box">
                    <div class="summary-label">Total Items</div>
                    <div class="summary-value"><?= count($bbu_items) ?></div>
                </div>
                <div class="summary-box">
                    <div class="summary-label">Total Quantity</div>
                    <div class="summary-value"><?= number_format($total_quantity, 3) ?></div>
                </div>
                <div class="summary-box">
                    <div class="summary-label">Total Amount</div>
                    <div class="summary-value">₹ <?= number_format($total_amount, 2) ?></div>
                </div>
            </div>
            
            <div class="amount-words">
                <strong>Amount in Words:</strong> <?= numberToWords($total_amount) ?>
            </div>
        </div>

        <!-- Signatures -->
        <div class="signatures">
            <div class="signature-line">
                <div class="line"></div>
                <div class="label">Prepared By</div>
                <div class="label" style="margin-top: 5px;">(<?= htmlspecialchars($bbu_data['created_by_name'] ?? '_________________') ?>)</div>
            </div>
            <div class="signature-line">
                <div class="line"></div>
                <div class="label">Checked By</div>
                <div class="label" style="margin-top: 5px;">(_________________)</div>
            </div>
            <div class="signature-line">
                <div class="line"></div>
                <div class="label">Approved By</div>
                <div class="label" style="margin-top: 5px;">(_________________)</div>
            </div>
        </div>

        <!-- Footer -->
        <div class="print-footer">
            This is a computer generated document and does not require signature.<br>
            Generated on: <?= date('d-m-Y h:i A') ?>
        </div>
    </div>
</div>

<script>
// Print functionality
function downloadAsPDF() {
    // For PDF download, we trigger print and user can save as PDF
    window.print();
}

// Add print optimization
window.onbeforeprint = function() {
    document.body.style.background = 'white';
    document.body.style.padding = '0';
};

window.onafterprint = function() {
    document.body.style.background = '#e5e7eb';
    document.body.style.padding = '20px';
};

// Keyboard shortcut (Ctrl+P)
document.addEventListener('keydown', function(e) {
    if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
        e.preventDefault();
        window.print();
    }
});
</script>

</body>
</html>

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