<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!isset($_SESSION['user_id'])) {
    header("Location: auth-basic-signin.php");
    exit();
}

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

$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();

$customerId = isset($_GET['customer_id']) ? (int)$_GET['customer_id'] : 0;
$cid = $customerId;

// Optional customer for breadcrumb
$cust = null;
if ($customerId > 0) {
    $cs = $conn->prepare("SELECT name FROM permanentcustomer WHERE id=?");
    $cs->bind_param("i", $customerId);
    $cs->execute();
    $cr = $cs->get_result();
    $cust = $cr->fetch_assoc();
    $cs->close();
}

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_temp_invoice'])) {
	$id = intval($_POST['id'] ?? 0);
	if ($id) {
		$stmt = $conn->prepare("DELETE FROM permanentcustomerinvoice WHERE id=?");
		$stmt->bind_param("i", $id);
		if ($stmt->execute()) {
			echo json_encode(['status'=>'success']);
		} else {
			echo json_encode(['status'=>'error','message'=>$stmt->error]);
		}
		$stmt->close();
		exit;
	}
	echo json_encode(['status'=>'error','message'=>'Invalid id']);
	exit;
}

// Fetch list (optionally filtered by customer)
if ($customerId > 0) {
	$stmt = $conn->prepare("SELECT t.*, c.name AS customer_name FROM permanentcustomerinvoice t LEFT JOIN customers c ON c.id=t.customer_id WHERE t.customer_id=? ORDER BY t.id DESC");
	$stmt->bind_param("i", $customerId);
} else {
	$stmt = $conn->prepare("SELECT t.*, c.name AS customer_name FROM permanentcustomerinvoice t LEFT JOIN customers c ON c.id=t.customer_id ORDER BY t.id DESC");
}
$stmt->execute();
$result = $stmt->get_result();
$rows = [];
while ($r = $result->fetch_assoc()) { $rows[] = $r; }
$stmt->close();
?>

<!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" />
	<link href="assets/plugins/datatable/css/dataTables.bootstrap5.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>
/* Selected value box */
.select2-container--default .select2-selection--single {
    background-color: #171717 !important;   /* background color */
    color: #ffffff !important;              /* text color */
    border: 1px solid #444;      /* border color */
    height: 40px;
}

/* Placeholder text */
.select2-container--default .select2-selection--single .select2-selection__placeholder {
    color: #bbb !important;  /* placeholder color */
}

/* Dropdown items */
.select2-container--default .select2-results__option {
    background-color: #171717 !important;   /* dropdown background */
    color: #fff !important;                 /* text color */
}

/* Hover/active dropdown item */
.select2-container--default .select2-results__option--highlighted {
    background-color: #171717 !important;      /* hover background */
    color: #fff !important;                 /* hover text color */
}

/* Dropdown arrow icon */
.select2-container--default .select2-selection__arrow b {
    border-color: #fff transparent transparent transparent; /* arrow color */
}
.select2-container--default .select2-selection--single .select2-selection__rendered {
    color: #fff !important;
    line-height: 28px;
}
.select2-dropdown {
    background-color: #171717 !important;
    
}
.select2-container--default .select2-search--dropdown .select2-search__field {
    border: 1px solid #aaa;
    background: #171717 !important;
    color: #FFF !important;
}
.select2-container--default .select2-selection--single .select2-selection__clear { 
    color: #FFF !important;
    
}
 #example2 th, #example2 td { white-space: nowrap; vertical-align: middle; }

</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">Customer Name</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"><?= htmlspecialchars($cust['name'] ?? 'Unknown'); ?></li>
							</ol>
						</nav>
					</div> 
					<div class="ms-auto">
					<div class="btn-group">
						<a href="permanent-customer.php" class="btn btn-secondary">Back</a>
					</div> 
					</div>
				</div>
				<!--end breadcrumb-->
				 
                <h6 class="mb-0 text-uppercase">Invoice History</h6>
				<hr/>
				<div class="card">
					<div class="card-body">
                        <div class="table-responsive">
                            <table id="example2" class="table table-striped table-bordered text-center">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Customer</th>
                                        <th>Invoice No</th>
                                        <th>Invoice Date</th>
                                        <th>Products</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (count($rows) === 0): ?>
                                    <tr>
                                        <td colspan="6" class="text-center">No invoices found.</td>
                                    </tr>
                                    <?php endif; ?>
                                    <?php foreach ($rows as $i => $r): ?>
                                    <tr>
                                        <td><?= $i+1 ?></td>
                                        <td><?= htmlspecialchars($r['customer_name'] ?? $r['customer_id']) ?></td>
                                        <td><?= htmlspecialchars($r['invoice_number']) ?></td>
                                        <td><?= htmlspecialchars($r['invoice_date']) ?></td>
                                        <td>
                                            <?php 
                                                $products = json_decode($r['products_data'] ?? '[]', true);
                                                if (is_array($products)) {
                                                    $names = array_map(function($p){ return htmlspecialchars($p['product_name'] ?? ''); }, $products);
                                                    echo implode(', ', array_filter($names));
                                                }
                                            ?>
                                        </td>
                                        <td>
                                            <div class="d-flex justify-content-center">
                                                <a href="permanent-customer-invoice.php?id=<?= $r['id'] ?>" target="_blank" class="btn btn-sm btn-light me-2" title="Print"><i class='bx bxs-printer'></i></a>
                                                 <button class="btn btn-sm btn-danger deleteTempBtn" data-id="<?= $r['id'] ?>" title="Delete"><i class='bx bxs-trash'></i></button>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
					</div>
				</div>
			</div>
		</div>  
                      
		
		<!-- Edit Item Modal start -->
		<div class="modal fade" id="editItemModal" tabindex="-1" aria-hidden="true">
			<div class="modal-dialog modal-dialog-centered" role="document">
				<div class="modal-content">
					<form id="editItemForm" method="post">
						<div class="modal-header">
							<h5 class="modal-title">Edit Item</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="id" id="edit_item_id" />
							<div class="row g-2 mb-3">
								<div class="col mb-0">
									<label class="form-label" for="edit_shop_name">Farm Name</label>
									<input type="text" id="edit_shop_name" name="shop_name" class="form-control" required />
								</div>
								<div class="col mb-0">
									<label class="form-label" for="edit_owner_name">Customer Name</label>
									<input type="text" id="edit_owner_name" name="owner_name" class="form-control" required />
								</div>
							</div>
							<div class="row g-2 mb-3">
								<div class="col mb-0">
									<label class="form-label" for="edit_address">Address</label>
									<input type="text" id="edit_address" name="address" class="form-control" />
								</div>
								<div class="col mb-0">
									<label class="form-label" for="edit_product_name">Product</label>
									<input type="text" id="edit_product_name" name="product_name" class="form-control" required />
								</div>
							</div>
							<div class="row g-2 mb-3">
								<div class="col mb-0">
									<label class="form-label" for="edit_hsn_code">HSN Code</label>
									<input type="text" id="edit_hsn_code" name="hsn_code" class="form-control" />
								</div>
								<div class="col mb-0">
									<label class="form-label" for="edit_bill_number">Bill No</label>
									<input type="text" id="edit_bill_number" name="bill_number" class="form-control" />
								</div>
							</div>
							<div class="row g-2 mb-3">
								<div class="col mb-0">
									<label class="form-label" for="edit_bill_date">Bill Date</label>
									<input type="date" id="edit_bill_date" name="bill_date" class="form-control" />
								</div>
								<div class="col mb-0">
									<label class="form-label" for="edit_quantity">Quantity</label>
									<input type="number" id="edit_quantity" name="quantity" class="form-control" required />
								</div>
							</div>
							<div class="row g-2 mb-3">
								<div class="col mb-0">
									<label class="form-label" for="edit_price">Price</label>
									<input type="number" step="0.01" id="edit_price" name="price" class="form-control" readonly />
								</div>
								<div class="col mb-0">
									<label class="form-label" for="edit_total_amount">Total Amount</label>
									<input type="number" step="0.01" id="edit_total_amount" name="total_amount" class="form-control" readonly />
								</div>
							</div>
							<div class="row g-2 mb-3">
								<div class="col mb-0">
									<label class="form-label" for="edit_fullpaymentreceived">Full Payment Received</label>
									<select id="edit_fullpaymentreceived" name="full_payment_received" class="form-control">
										<option value="yes">Yes</option>
										<option value="no">No</option>
									</select>
								</div>
								<div class="col mb-0" id="edit_amount_box" style="display:none;">
									<label class="form-label" for="edit_amount_payment">Received Amount</label>
									<input type="number" step="0.01" id="edit_amount_payment" name="amount_payment" class="form-control" />
								</div>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
							<button type="submit" id="editItemSave" class="btn btn-primary">Save</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		<!-- Edit Item Modal end -->

		<!-- Delete Item Modal start -->
		<div class="modal fade" id="deleteItemModal" tabindex="-1" aria-hidden="true">
			<div class="modal-dialog modal-dialog-centered" role="document">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title">Delete Item</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body">
						<p>Are you sure you want to delete <strong id="delete_item_name"></strong>?</p>
						<input type="hidden" id="delete_item_id" />
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">No</button>
						<button type="button" id="confirmDeleteItem" class="btn btn-danger">Yes, Delete</button>
					</div>
				</div>
			</div>
		</div>
		<!-- Delete Item Modal end -->
                         
		<!--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>
	<!--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>
	<script src="assets/plugins/datatable/js/jquery.dataTables.min.js"></script>
	<script src="assets/plugins/datatable/js/dataTables.bootstrap5.min.js"></script>
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>


	<!-- <script>
		$(document).ready(function() {
			$('#example').DataTable(
			  
			  );
			$("div.dataTables_filter input").focus();
		  } );
	</script> -->
	
	
	<script>
	  
	  $(document).ready(function() {
	  $('#example').DataTable()
	});
	  
	</script>
	
	
	<script>
		$(document).ready(function() {
			var table = $('#example2').DataTable( {
				lengthChange: false,
				buttons: [ 'copy', 'excel', 'pdf', 'print']
			} );
		 
			table.buttons().container()
				.appendTo( '#example2_wrapper .col-md-6:eq(0)' );
		} );
	</script>
	<!--app JS-->
	<script src="assets/js/app.js"></script> 


<!-- Select2 CSS -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<!-- Select2 JS -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(function(){
	$('#historyTable').DataTable({
		lengthChange:false,
		buttons: []
	});

	// Delete
	$(document).on('click', '.deleteTempBtn', function(){
		if(!confirm('Delete this invoice?')) return;
		const id = $(this).data('id');
		$.ajax({
			url: '',
			type: 'POST',
			dataType: 'json',
			data: { delete_temp_invoice: 1, id: id },
			success: function(res){
				if(res.status==='success'){
					toastr.success('Deleted');
					location.reload();
				}else{
					toastr.error(res.message||'Delete failed');
				}
			},
			error: function(){ toastr.error('Server error'); }
		});
	});

	// Create Multiple Invoice button (navigate back to page with modal)
	$('#createMultiBtn').on('click', function(){
		window.location.href = 'temporary-table.php?customer_id=<?= $customerId ?>#open-multi';
	});
});
</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>

