<?php
session_start();
if(!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}

include('../includes/db.php');

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

$sql = "SELECT * FROM manual_entries WHERE id = $id";
$result = mysqli_query($conn, $sql);
$entry = mysqli_fetch_assoc($result);

if(!$entry) {
    header("Location: manual_entries_list.php");
    exit();
}
?>

<?php include('../includes/log.php'); ?>
<?php include('../includes/sd.php'); ?>

<div class="view-entry-container" id="print-content">
    <!-- Header -->
    <div class="invoice-header">
        <div class="company-info">
            <h1>ALFATEH PETROLEUM SERVICE</h1>
            <p>Main Sujawal Road Tando Muhammad Khan</p>
            <p>Phone: 1234-5678901 | NTN: 1234567-8</p>
        </div>
        <div class="invoice-title">
            <h2>MANUAL ENTRY DETAILS</h2>
            <p>Entry #: <?php echo htmlspecialchars($entry['entry_no']); ?></p>
        </div>
    </div>

    <div class="entry-details">
        <div class="details-row">
            <div class="detail-item">
                <span class="label">Entry Date:</span>
                <span class="value"><?php echo date('d-m-Y', strtotime($entry['entry_date'])); ?></span>
            </div>
            <div class="detail-item">
                <span class="label">Vehicle Number:</span>
                <span class="value"><?php echo htmlspecialchars($entry['vehicle_no'] ?: '—'); ?></span>
            </div>
            <div class="detail-item">
                <span class="label">Customer Name:</span>
                <span class="value"><?php echo htmlspecialchars($entry['customer_name'] ?: '—'); ?></span>
            </div>
        </div>
    </div>

    <!-- Items Table -->
    <table class="items-table">
        <thead>
            <tr>
                <th>#</th>
                <th>Description</th>
                <th>Rate (Rs/L)</th>
                <th>Liters</th>
                <th>Amount (Rs)</th>
            </tr>
        </thead>
        <tbody>
            <?php if($entry['hsd_liters'] > 0): ?>
            <tr>
                <td>1</div>
                <td>HSD (Diesel)</div>
                <td><?php echo number_format($entry['hsd_rate'], 2); ?></div>
                <td><?php echo number_format($entry['hsd_liters'], 2); ?> L</div>
                <td><?php echo number_format($entry['hsd_liters'] * $entry['hsd_rate'], 2); ?></div>
            </tr>
            <?php endif; ?>
            <?php if($entry['super_liters'] > 0): ?>
            <tr>
                <td><?php echo $entry['hsd_liters'] > 0 ? '2' : '1'; ?></div>
                <td>Super (Petrol)</div>
                <td><?php echo number_format($entry['super_rate'], 2); ?></div>
                <td><?php echo number_format($entry['super_liters'], 2); ?> L</div>
                <td><?php echo number_format($entry['super_liters'] * $entry['super_rate'], 2); ?></div>
            </tr>
            <?php endif; ?>
            <?php if($entry['other_liters'] > 0): ?>
            <tr>
                <td><?php echo ($entry['hsd_liters'] > 0 ? 1 : 0) + ($entry['super_liters'] > 0 ? 1 : 0) + 1; ?></div>
                <td>Other</div>
                <td><?php echo number_format($entry['other_rate'], 2); ?></div>
                <td><?php echo number_format($entry['other_liters'], 2); ?> L</div>
                <td><?php echo number_format($entry['other_liters'] * $entry['other_rate'], 2); ?></div>
            </tr>
            <?php endif; ?>
        </tbody>
        <tfoot>
            <tr class="total-row">
                <td colspan="4" class="text-right"><strong>GRAND TOTAL</strong></div>
                <td class="total-amount">Rs <?php echo number_format($entry['total_amount'], 2); ?></div>
            </tr>
        </tfoot>
    </table>

    <?php if($entry['notes']): ?>
    <div class="notes-section">
        <h4>Notes:</h4>
        <p><?php echo nl2br(htmlspecialchars($entry['notes'])); ?></p>
    </div>
    <?php endif; ?>

    <div class="signature-section">
        <div class="signature-line">
            <span>_____________________</span>
            <span>Authorized Signature</span>
        </div>
        <div class="print-date">
            Printed on: <?php echo date('d-m-Y h:i A'); ?>
        </div>
    </div>
</div>

<div class="action-buttons">
    <button onclick="window.print()" class="btn-print"><i class="fas fa-print"></i> Print</button>
    <button onclick="downloadPDF()" class="btn-pdf"><i class="fas fa-file-pdf"></i> Download PDF</button>
    <a href="manual_entries_list.php" class="btn-back"><i class="fas fa-arrow-left"></i> Back to List</a>
</div>

<style>
.view-entry-container {
    max-width: 900px;
    margin: 20px auto;
    background: #fff;
    padding: 30px;
    border-radius: 16px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.invoice-header {
    text-align: center;
    border-bottom: 2px solid #A04657;
    padding-bottom: 20px;
    margin-bottom: 20px;
}

.company-info h1 {
    color: #A04657;
    margin: 0;
    font-size: 24px;
}

.company-info p {
    margin: 5px 0;
    font-size: 12px;
    color: #666;
}

.invoice-title h2 {
    margin: 15px 0 5px;
    font-size: 18px;
    color: #333;
}

.invoice-title p {
    font-size: 14px;
    font-weight: bold;
    color: #A04657;
}

.details-row {
    display: flex;
    gap: 30px;
    margin-bottom: 25px;
    background: #f8f9fa;
    padding: 15px;
    border-radius: 10px;
}

.detail-item {
    flex: 1;
}

.detail-item .label {
    font-weight: 600;
    color: #666;
    font-size: 12px;
    display: block;
}

.detail-item .value {
    font-size: 14px;
    font-weight: 600;
    color: #333;
}

.items-table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
}

.items-table th {
    background: #f8f9fa;
    padding: 12px;
    font-weight: 700;
    color: #555;
    border-bottom: 2px solid #e0e0e0;
    text-align: left;
}

.items-table td {
    padding: 10px 12px;
    border-bottom: 1px solid #f0f0f0;
}

.items-table .total-row {
    background: #f8f9fa;
    font-weight: bold;
}

.total-amount {
    font-size: 18px;
    font-weight: 800;
    color: #A04657;
}

.text-right {
    text-align: right;
}

.notes-section {
    margin: 20px 0;
    padding: 15px;
    background: #fef5f7;
    border-radius: 10px;
}

.notes-section h4 {
    margin: 0 0 10px;
    color: #A04657;
    font-size: 14px;
}

.notes-section p {
    margin: 0;
    font-size: 13px;
    line-height: 1.5;
}

.signature-section {
    margin-top: 40px;
    padding-top: 20px;
    border-top: 1px dashed #ddd;
    text-align: center;
}

.signature-line {
    margin: 20px 0;
}

.signature-line span:first-child {
    display: inline-block;
    width: 200px;
    border-top: 1px solid #333;
    margin: 0 20px;
}

.print-date {
    font-size: 10px;
    color: #999;
}

.action-buttons {
    text-align: center;
    margin: 20px auto;
    display: flex;
    gap: 15px;
    justify-content: center;
}

.btn-print, .btn-pdf, .btn-back {
    padding: 10px 25px;
    border-radius: 8px;
    font-weight: 600;
    font-size: 13px;
    border: none;
    cursor: pointer;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.btn-print {
    background: #6c5ce7;
    color: #fff;
}

.btn-print:hover {
    background: #5a4bd1;
    transform: translateY(-2px);
}

.btn-pdf {
    background: #dc3545;
    color: #fff;
}

.btn-pdf:hover {
    background: #c82333;
    transform: translateY(-2px);
}

.btn-back {
    background: #6c757d;
    color: #fff;
}

.btn-back:hover {
    background: #5a6268;
    transform: translateY(-2px);
    color: #fff;
}

@media print {
    .action-buttons, .sidebar, .navbar-custom, footer {
        display: none !important;
    }
    .view-entry-container {
        margin: 0;
        padding: 0;
        box-shadow: none;
    }
}

@media (max-width: 768px) {
    .view-entry-container {
        padding: 15px;
        margin: 10px;
    }
    .details-row {
        flex-direction: column;
        gap: 10px;
    }
    .action-buttons {
        flex-direction: column;
        align-items: center;
    }
    .btn-print, .btn-pdf, .btn-back {
        width: 100%;
        justify-content: center;
    }
}
</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

<script>
async function downloadPDF() {
    const element = document.getElementById('print-content');
    if (!element) {
        alert('No content to download');
        return;
    }

    const pdfBtn = document.querySelector('.btn-pdf');
    const originalHTML = pdfBtn.innerHTML;
    pdfBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating PDF...';
    pdfBtn.disabled = true;

    try {
        const canvas = await html2canvas(element, {
            scale: 2,
            useCORS: true,
            logging: false,
            backgroundColor: '#ffffff'
        });

        const imgData = canvas.toDataURL('image/png');
        const imgWidth = 210;
        const pageHeight = 297;
        const pageWidth = imgWidth - 20;
        const imgHeight = (canvas.height * pageWidth) / canvas.width;
        
        const { jsPDF } = window.jspdf;
        const pdf = new jsPDF('p', 'mm', 'a4');
        
        let remainingHeight = imgHeight;
        let sourceY = 0;
        let pageNum = 1;
        const canvasHeight = canvas.height;
        const topMargin = 10;
        const availableHeight = pageHeight - topMargin - 15;

        while (remainingHeight > 0) {
            let sliceHeight = Math.min(remainingHeight, availableHeight);
            const sourceHeightPx = (sliceHeight / imgHeight) * canvasHeight;

            pdf.addImage(
                imgData, 'PNG',
                10, topMargin,
                pageWidth, sliceHeight,
                undefined, 'FAST',
                0,
                0, sourceY,
                canvas.width, sourceHeightPx
            );

            remainingHeight -= sliceHeight;
            sourceY += sourceHeightPx;

            if (remainingHeight > 0) {
                pdf.addPage();
                pageNum++;
            }
        }

        const fileName = `Manual_Entry_<?php echo $entry['entry_no']; ?>.pdf`;
        pdf.save(fileName);

    } catch (error) {
        console.error('Error generating PDF:', error);
        alert('An error occurred while generating the PDF. Please try again.');
    } finally {
        pdfBtn.innerHTML = originalHTML;
        pdfBtn.disabled = false;
    }
}
</script>

<?php include('../includes/ft.php'); ?>