<?php
require_once __DIR__ . '/../inc/db.php';

$id = intval($_GET['id'] ?? 0);
if ($id <= 0) {
    die('Invalid invoice ID.');
}

$user_id = $_SESSION['user_id'];

// Fetch user data
$sql = "SELECT name, email, phone, mobile, address, instagram, facebook, profile_image 
        FROM users WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();


$stmt = $conn->prepare("SELECT * FROM invoices WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();
$invoice = $result->fetch_assoc();

if (!$invoice) {
    die('Invoice not found.');
}

// अब $invoice में आपकी पूरी invoice details हैं
?>

<!doctype html>
<html lang="en">

<head>
	<!-- Required meta tags -->
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<!--favicon-->
	<link rel="icon" href="assets/images/logo-icon.png" type="image/png" />
	<!--plugins-->
	<link href="assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
	<link href="assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet" />
	<link href="assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet" />
	<!-- loader-->
	<link href="assets/css/pace.min.css" rel="stylesheet" />
	<script src="assets/js/pace.min.js"></script>
	<!-- Bootstrap CSS -->
	<link href="assets/css/bootstrap.min.css" rel="stylesheet">
	<link href="assets/css/bootstrap-extended.css" rel="stylesheet">
	<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
	<link href="assets/css/app.css" rel="stylesheet">
	<link href="assets/css/icons.css" rel="stylesheet">
	
	<title>Kumawat</title>
	
<style>
		@media print {
			/* Set the page size to A4 */
			@page {
				size: A4;
				margin-top:0;
				margin-bottom:0;
			}
			 @page :footer {
                    display: none !important;
                }
            
                @page :header {
                    display: none !important;
                } 
			/* Hide the elements you don't want to print */
			.toolbar,
			.sidebar-wrapper,
			.topbar,
			.page-breadcrumb,
			.switcher-wrapper,
			.page-footer,
			.overlay,
			.back-to-top {
				display: none !important;
			}
			title {
				display: none;
			}
			/* Keep the invoice content visible */
			#invoice {
				width: 100% !important;
				margin: 0 !important;
				padding: 0 !important;
			}
			
			/* Adjust the card and body for a clean printout */
			.card, .card-body {
				border: none !important;
				box-shadow: none !important;
				padding: 0 !important;
				margin: 0 !important;
			}
			
			/* Ensure main content takes full width */
			.page-wrapper, .page-content, .wrapper {
				padding: 0 !important;
				margin: 0 !important;
				width: 100% !important;
				min-width: unset !important;
			}
	

		/* General styling for the page */
		body {
			font-family: 'Roboto', sans-serif;
			background-color: #f0f2f5;
		}
		
		.invoice {
			background-color: #fff;
			padding: 20px;
			min-width: 600px;
			page-break-inside: avoid;
		}

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

		.contacts {
			margin-bottom: 20px;
		}

		.invoice-details {
			text-align: right;
		}
		
		table {
        width: 100%;
        border-collapse: collapse; /* Ensure single border between cells */
        margin-bottom: 20px;  
    } 

    th, td {
        border: 1px solid #000 !important; /* vertical + horizontal borders for all cells */
        padding: 8px; /* thoda spacing for readability */
        text-align: left;
    }

    thead th {
        background-color: #f8f9fa !important;
    }

    tfoot td {
        font-weight: bold;
    }
    .fthree{
         border-bottom: none !important;
         border-top: none !important;
    }
    .ffour{
         border-bottom: none !important;
         border-top: none !important;
    }
    .ffive{ 
         border-top: none !important;
    }
		.thanks {
		     border: none !important;
			margin-top: 20px;
			font-weight: bold;
			font-size: 1.2rem;
			page-break-inside: avoid;
		}
		
		.notices {
			margin-top: 20px;
			font-size: 0.8rem;
		}
		.signature-seal {
        display: flex;
        justify-content: space-between;
        margin-top: 50px; /* space above signature */
        page-break-inside: avoid; /* keep signature & seal together */
    }

    .signature-seal .sign, 
    .signature-seal .seal {
        text-align: center;
    }

    .signature-seal .sign p {
        margin: 0;
        font-weight: bold;
    }

    .signature-seal .seal img {
        display: block;
        margin: 0 auto;
    }
	}
	.signature-seal {
	    display:none;
	}
	</style>







</head>

<body class="bg-theme bg-theme2">
	<!--wrapper-->
	<div class="wrapper">
		<!--sidebar wrapper -->
		<div class="sidebar-wrapper" data-simplebar="true">
			<div class="sidebar-header">
				<div>
					<img src="assets/images/logo-icon.png" class="logo-icon" alt="logo icon">
				</div>
				<div>
					<h4 class="logo-text">Kumawat</h4>
				</div>
				<div class="toggle-icon ms-auto"><i class='bx bx-arrow-back'></i>
				</div>
			 </div>
			<!--navigation-->
			<ul class="metismenu" id="menu">
				<li>
					<a href="index.php">
						<div class="parent-icon"><i class='bx bx-home-alt'></i>
						</div>
						<div class="menu-title">Home</div>
					</a> 
				</li>  
				<li>
					<a href="table-datatable.php">
						<div class="parent-icon"><i class="bx bx-grid-alt"></i>
						</div>
						<div class="menu-title">Product Tables</div>
					</a> 
				</li>
			  
				<li>
					<a href="ecommerce-products.php">
						<div class="parent-icon"><i class='bx bx-briefcase-alt'></i>
						</div>
						<div class="menu-title">Products</div>
					</a> 
				</li>  
				<li>
					<a href="ecommerce-add-new-products.php">
						<div class="parent-icon"><i class='bx bx-store'></i>
						</div>
						<div class="menu-title">Add New Products</div>
					</a> 
				</li> 
				<li>
					<a href="temprary.php">
						<div class="parent-icon"><i class='bx bx-repeat'></i>
						</div>
						<div class="menu-title">Temporary</div>
					</a> 
				</li> 
				<li>
					<a href="permanent-customer.php">
						<div class="parent-icon"><i class='bx bx-bookmark-heart'></i>
						</div>
						<div class="menu-title">Permanent Customer</div>
					</a> 
				</li>
				<li>
					<a href="party-customer.php">
						<div class="parent-icon"><i class='bx bx-cookie'></i>
						</div>
						<div class="menu-title">Party</div>
					</a> 
				</li>
				<li>
					<a href="ecommerce-orders.php">
						<div class="parent-icon"><i class='bx bx-cart'></i>
						</div>
						<div class="menu-title">History</div>
					</a> 
				</li> 
				<li>
					<a href="user-profile.php">
						<div class="parent-icon"><i class="bx bx-user-circle"></i>
						</div>
						<div class="menu-title">User Profile</div>
					</a>
				</li>  
			</ul>
			<!--end navigation-->
		</div>
		<!--end sidebar wrapper -->
		<!--start header -->
		<header>
			<div class="topbar d-flex align-items-center">
				<nav class="navbar navbar-expand gap-3">
					<div class="mobile-toggle-menu"><i class='bx bx-menu'></i>
					</div>
					<div class="search-bar flex-grow-1">
						<div class="position-relative search-bar-box">
							<input type="text" class="form-control search-control" placeholder="Type to search..."> <span class="position-absolute top-50 search-show translate-middle-y"><i class='bx bx-search'></i></span>
							<span class="position-absolute top-50 search-close translate-middle-y"><i class='bx bx-x'></i></span>
						</div>
					</div>
					<div class="top-menu ms-auto">
						<ul class="navbar-nav align-items-center gap-1">
							<li class="nav-item mobile-search-icon d-flex d-lg-none" data-bs-toggle="modal" data-bs-target="#SearchModal">
								<a class="nav-link" href="avascript:;"><i class='bx bx-search'></i>
								</a>
							</li>  
						</ul>
					</div>
					<div class="user-box dropdown px-3">
						<a class="d-flex align-items-center nav-link dropdown-toggle gap-3 dropdown-toggle-nocaret" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
							<img src="<?= htmlspecialchars($user['profile_image'] ?: 'assets/images/avatars/avatar-2.png') ?>"
                                             alt="Profile" class="user-img">
							<div class="user-info">
								<p class="user-name mb-0"><?= htmlspecialchars($user['name']) ?></p>
								<p class="designattion mb-0"><?= htmlspecialchars($user['email']) ?></p>
							</div>
						</a>
						<ul class="dropdown-menu dropdown-menu-end">
							<li><a class="dropdown-item d-flex align-items-center" href="user-profile.php"><i class="bx bx-user fs-5"></i><span>Profile</span></a>
							</li> 
							<li>
								<div class="dropdown-divider mb-0"></div>
							</li>
							<li><a class="dropdown-item d-flex align-items-center" href="logout.php"><i class="bx bx-log-out-circle"></i><span>Logout</span></a>
							</li>
						</ul>
					</div>
				</nav>
			</div>
		</header>
		<!--end header -->
		<!--start page wrapper -->
		<div class="page-wrapper">
			<div class="page-content">
				<!--breadcrumb-->
				<div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
					<div class="breadcrumb-title pe-3">Applications</div>
					<div class="ps-3">
						<nav aria-label="breadcrumb">
							<ol class="breadcrumb mb-0 p-0">
								<li class="breadcrumb-item"><a href="javascript:;"><i class="bx bx-home-alt"></i></a>
								</li>
								<li class="breadcrumb-item active" aria-current="page">Invoice</li>
							</ol>
						</nav>
					</div> 
				</div>
				<!--end breadcrumb-->
				<div class="card">
					<div class="card-body">
						<div id="invoice">
							<div class="toolbar hidden-print">
								<div class="text-end">
								    <a href="pdf-view.php?id=<?= $id ?>" target="_blank" class="btn btn-danger">
                                       <i class="fa fa-file-pdf-o"></i>View Invoice
                                    </a>
									<button type="button" class="btn btn-dark" id="printBtn" data-id="<?php echo $invoice['id']; ?>"><i class="fa fa-print"></i> Print</button>
									<button type="button" id="exportPdfBtn" data-id="<?php echo $invoice['id']; ?>" class="btn btn-danger"><i class="fa fa-file-pdf-o"></i> Export as PDF</button>
									
								</div>
								<hr/> 
							</div>
							<div class="invoice overflow-auto">
								<div style="min-width: 600px">
									<header>
										<div class="row">
											<div class="col">
												<a href="javascript:;">
													<img src="assets/images/logo-icon.png" width="80" alt="" />
												</a>
											</div>
											<div class="col company-details">
												<h5 class="name">
									<a target="_blank" href="javascript:;">
									Kumawat Computer & Cyber Cafe
									</a>
								</h5> 
												<div>Behind Vendata College Reengus Sikar</div> 
												<div>kumawatcomputer@gmail.com</div>
												<div>+91 8742801906</div>
											</div>
										</div>
									</header>
									<main>
										<div class="row contacts">
											<div class="col invoice-to">
												<div class="text-gray-light">INVOICE TO:</div>
												<h2 class="to"><?= htmlspecialchars($invoice['party_name']) ?></h2>
												<div class="address"><?= htmlspecialchars($invoice['business_name']) ?></div>  
												<div class="email"><?= htmlspecialchars($invoice['gst_number']) ?></div>
												<div class="email"><?= htmlspecialchars($invoice['party_address']) ?></div>
											</div>
											<div class="col invoice-details">
												<h1 class="invoice-id">INVOICE - <?= htmlspecialchars($invoice['invoice_id']) ?></h1>
												<?php
                                                    $createdAt = $invoice['invoice_date']; // '2025-09-14 10:23:45' जैसी डेट
                                                    $formattedDate = date('d-M-Y', strtotime($createdAt)); // '14-Sep-2025'
                                                    ?>
												<div class="date">Date of Invoice: <?= $formattedDate ?></div>
												<!--<div class="date">Due Date: 30/10/2018</div>-->
											</div>
										</div>
										<?php
                                            $products = json_decode($invoice['products_json'], true);
                                            
                                            $subtotal = 0;
                                            $sn = 1;
                                            
                                            if ($products): ?>
										<table>
											<thead>
												<tr>
													<th>SN No.</th>
													<th class="text-left">Name</th>
													<th class="text-end">Quantity</th> 
													<th class="text-end">Sell Price</th>
													<th class="text-end">TOTAL</th>
												</tr>
											</thead>
											<tbody>
											    <?php foreach($products as $p): 
                                                    $total = floatval($p['sell_price']) * floatval($p['quantity']);
                                                    $subtotal += $total;
                                                ?>
												<tr>
													<td class="no"><?= $sn++ ?></td>
													<td class="text-left"><?= htmlspecialchars($p['name']) ?></td>
													<td class="unit text-left"><?= htmlspecialchars($p['quantity']) ?></td>
													<td class="qty text-left">₹<?= number_format($p['sell_price'], 2) ?></td>
													<td class="total text-left">₹<?= number_format($total, 2) ?></td> 
												</tr> 
												<?php endforeach; ?>
											</tbody>
											<tfoot class="fone">
												<tr class="ftwo">
													<td colspan="2" class="fthree"></td>
													<td colspan="2">SUBTOTAL</td>
													<td>₹<?= number_format($subtotal, 2) ?></td>
												</tr>
												<?php
                                                    $taxRate = 0.18; 
                                                    $tax = $subtotal * $taxRate;
                                                    $grandTotal = $subtotal + $tax;
                                                    ?>
												<tr>
													<td colspan="2" class="ffour"></td>
													<td colspan="2" class="ffive" >TAX 18%</td>
													<td>₹<?= number_format($tax, 2) ?></td>
												</tr>
												<tr>
													<td colspan="2" class="ffive"></td>
													<td colspan="2"  >GRAND TOTAL</td>
													<td>₹<?= number_format($grandTotal, 2) ?></td>
												</tr>
											</tfoot>
										</table>
										<?php endif; ?>
										<!--<div class="thanks">Thank you!</div>-->
										 <div class="signature-seal">
                                        <div class="sign">
                                            <p>_________________________</p>
                                            <p>Authorized Signatory</p>
                                        </div>
                                        <div class="seal">
                                            <img src="seal.png" alt="Company Seal" width="100">
                                        </div>
                                    </div>
										<div class="notices">
											<div>NOTICE:</div>
											<div class="notice">A finance charge of 1.5% will be made on unpaid balances after 30 days.</div>
										</div>
									</main>
									<footer>Invoice was created on a computer and is valid without the signature and seal.</footer>
								</div>
								<!--DO NOT DELETE THIS div. IT is responsible for showing footer always at the bottom-->
								<div></div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<!--end page wrapper -->
		<!--start overlay-->
		<div class="overlay toggle-icon"></div>
		<!--end overlay-->
		<!--Start Back To Top Button--> <a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
		<!--End Back To Top Button-->
		<footer class="page-footer">
			<p class="mb-0">Copyright © 2021. All right reserved.</p>
		</footer>
	</div>
	<!--end wrapper-->
	<!--start switcher-->
	<div class="switcher-wrapper">
		<div class="switcher-btn"> <i class='bx bx-cog bx-spin'></i>
		</div>
		<div class="switcher-body">
			<div class="d-flex align-items-center">
				<h5 class="mb-0 text-uppercase">Theme Customizer</h5>
				<button type="button" class="btn-close ms-auto close-switcher" aria-label="Close"></button>
			</div>
			<hr/>
			<p class="mb-0">Gaussian Texture</p>
			<hr>
			<ul class="switcher">
				<li id="theme1"></li>
				<li id="theme2"></li>
				<li id="theme3"></li>
				<li id="theme4"></li>
				<li id="theme5"></li>
				<li id="theme6"></li>
			</ul>
			<hr>
			<p class="mb-0">Gradient Background</p>
			<hr>
			<ul class="switcher">
				<li id="theme7"></li>
				<li id="theme8"></li>
				<li id="theme9"></li>
				<li id="theme10"></li>
				<li id="theme11"></li>
				<li id="theme12"></li>
				<li id="theme13"></li>
				<li id="theme14"></li>
				<li id="theme15"></li>
			  </ul>
		</div>
	</div>
	<div id="loadingOverlay" style="
    display:none !important;
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background:rgba(0,0,0,0.5);
    color:#fff;
    font-size:2rem;
    display:flex;
    align-items:center;
    justify-content:center;
    z-index:9999;
">
    Loading Invoice...
</div>
	<iframe id="pdfFrame" style="display:none;"></iframe>
	<!--end switcher-->
	<!-- Bootstrap JS -->
	<script src="assets/js/bootstrap.bundle.min.js"></script>
	<!--plugins-->
	<script src="assets/js/jquery.min.js"></script>
	<script src="assets/plugins/simplebar/js/simplebar.min.js"></script>
	<script src="assets/plugins/metismenu/js/metisMenu.min.js"></script>
	<script src="assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
	<!--app JS-->
	<script src="assets/js/app.js"></script>
	<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>
document.getElementById('exportPdfBtn').addEventListener('click', () => {
    const invoice = document.getElementById('invoice');

    html2canvas(invoice, {scale:2}).then(canvas => {
        const { jsPDF } = window.jspdf;
        const pdf = new jsPDF('p','mm','a4');
        const imgData = canvas.toDataURL('image/png');

        // पेज चौड़ाई/ऊँचाई में फिट करें
        const pageWidth  = pdf.internal.pageSize.getWidth();
        const pageHeight = pdf.internal.pageSize.getHeight();
        const imgProps = pdf.getImageProperties(imgData);
        const pdfHeight = (imgProps.height * pageWidth) / imgProps.width;

        pdf.addImage(imgData, 'PNG', 0, 0, pageWidth, pdfHeight);
        pdf.save(`Invoice-${Date.now()}.pdf`);
    });
});
</script>

<div id="loadingOverlay" style="
    display:none !important;
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background:rgba(0,0,0,0.5);
    color:#fff;
    font-size:2rem;
    display:flex;
    align-items:center;
    justify-content:center;
    z-index:9999;
">
    Loading Invoice...
</div>

<iframe id="pdfFrame" style="display:none;"></iframe> 

<script>
document.getElementById('printBtn').addEventListener('click', function(){
    var invoiceId = this.getAttribute('data-id');
    var iframe = document.getElementById('pdfFrame');
    var overlay = document.getElementById('loadingOverlay');

    // Show loading overlay
    overlay.style.display = 'flex';

    // Load PDF in iframe
    iframe.src = 'pdf-view.php?id=' + invoiceId;

    iframe.onload = function(){
        try {
            // Focus iframe
            iframe.contentWindow.focus();

            // Print after small delay to ensure PDF is ready
            setTimeout(function(){
                iframe.contentWindow.print();
                overlay.style.display = 'none'; // hide overlay after print dialog opens
            }, 1000); // 1 second delay, adjust if needed
        } catch(e) {
            console.error('Print failed:', e);
            overlay.style.display = 'none';
        }
    };
});
</script>
<script>
<script>
document.getElementById('exportPdfBtn').addEventListener('click', function() {
    var invoiceId = this.getAttribute('data-id');

    // Create a temporary link
    var link = document.createElement('a');
    link.href = 'pdf-view.php?id=' + invoiceId;
    link.download = 'invoice-' + invoiceId + '.pdf'; // sets filename for download
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
});
</script>
</body>

<script>'undefined'=== typeof _trfq || (window._trfq = []);'undefined'=== typeof _trfd && (window._trfd=[]),_trfd.push({'tccl.baseHost':'secureserver.net'},{'ap':'cpsh-oh'},{'server':'p3plzcpnl509132'},{'dcenter':'p3'},{'cp_id':'10399385'},{'cp_cl':'8'}) // Monitoring performance to make your website faster. If you want to opt-out, please contact web hosting support.</script><script src='https://img1.wsimg.com/traffic-assets/js/tccl.min.js'></script></html>