<?php
ob_start();
date_default_timezone_set('Asia/Kolkata');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// ==========================================
// INCLUDE DATABASE CONNECTION (PDO)
// ==========================================
@include 'db.php';
@include 'conn.php';
@include 'config.php';
@include 'db_connect.php';

if (!isset($pdo) || !($pdo instanceof PDO)) {
    try {
        $host = 'localhost';
        $db   = 'dubaiwhe_tyre';
        $user = 'dubaiwhe_user'; 
        $pass = ''; 
        $charset = 'utf8mb4';
        $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
        $pdo = new PDO($dsn, $user, $pass, [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ]);
    } catch (\PDOException $e) {
        die("<div style='font-family:sans-serif; padding:20px; color:red;'><h3>Database Connection Error</h3><p>" . htmlspecialchars($e->getMessage()) . "</p></div>");
    }
}

/* =========================================================
   PDF + EMAIL HELPERS
   ========================================================= */
function dw_pdf_escape(string $text): string {
    $text = str_replace(["\r", "\n"], ' ', $text);
    $text = iconv('UTF-8', 'windows-1252//TRANSLIT//IGNORE', $text);
    if ($text === false) $text = '';
    return str_replace(['\\','(',')'], ['\\\\','\\(','\\)'], $text);
}
function dw_pdf_wrap(string $text, int $maxChars=62): array {
    $text=trim(preg_replace('/\s+/', ' ', $text));
    if ($text==='') return [''];
    $words=preg_split('/\s+/', $text); $lines=[]; $line='';
    foreach($words as $word){
        if($line===''){ $line=$word; continue; }
        if(strlen($line.' '.$word)<=$maxChars) $line.=' '.$word;
        else { $lines[]=$line; $line=$word; }
    }
    if($line!=='') $lines[]=$line;
    return $lines ?: [''];
}
function dw_pdf_make_invoice(int $saleId, PDO $pdo, array $itemData, float $grandTotal, float $paidAmount, float $balanceAmount, string $saleDate, string $invoiceNo, ?array $customerInfo=null): string {
    $settings=[];
    try { $st=$pdo->query("SELECT * FROM settings LIMIT 1"); $settings=$st?($st->fetch(PDO::FETCH_ASSOC)?:[]):[]; } catch(Throwable $e) {}
    $shopName=(string)($settings['shop_name']??'DUBAI WHEELS');
    $shopAddress=(string)($settings['shop_address']??($settings['address']??''));
    $shopPhone=(string)($settings['shop_phone']??($settings['phone']??''));
    $shopGst=strtoupper(trim((string)($settings['gst_number']??($settings['gstin']??''))));
    $W=595.28; $H=841.89; $chunks=array_chunk($itemData,18); if(!$chunks)$chunks=[[]];
    $streams=[];
    foreach($chunks as $pageIndex=>$chunk){
        $ops=[]; $y=800;
        $txt=function($v,$x,$yy,$size=10,$bold=false)use(&$ops){$font=$bold?'/F2':'/F1';$ops[]="BT {$font} {$size} Tf 1 0 0 1 {$x} {$yy} Tm (".dw_pdf_escape((string)$v).") Tj ET";};
        $ln=function($x1,$y1,$x2,$y2)use(&$ops){$ops[]="{$x1} {$y1} m {$x2} {$y2} l S";};
        $rect=function($x,$yy,$w,$h)use(&$ops){$ops[]="{$x} {$yy} {$w} {$h} re S";};
        $txt($shopName,40,$y,18,true); $txt('TAX INVOICE',445,$y,13,true); $y-=22;
        foreach(dw_pdf_wrap($shopAddress,85) as $a){$txt($a,40,$y,9);$y-=12;}
        if($shopPhone!==''){$txt('Phone: '.$shopPhone,40,$y,9);$y-=12;}
        if($shopGst!==''){$txt('GSTIN: '.$shopGst,40,$y,9,true);$y-=12;}
        $ln(40,$y-4,555,$y-4);$y-=24;
        $txt('Invoice No:',40,$y,9,true);$txt($invoiceNo,105,$y,9);$txt('Date:',390,$y,9,true);$txt($saleDate,430,$y,9);$y-=18;
        $customerName=(string)($customerInfo['name']??'Walk-in Customer');$customerEmail=(string)($customerInfo['email']??'');
        $txt('Bill To:',40,$y,9,true);$txt($customerName,90,$y,9,true);$y-=13;
        if($customerEmail!==''){$txt('Email: '.$customerEmail,40,$y,8);$y-=13;}
        $top=$y-3;$hh=24;$rh=22;$x0=40;$x1=235;$x2=285;$x3=355;$x4=420;$x5=500;$x6=555;$bottom=$top-$hh-($rh*max(1,count($chunk)));
        $ops[]="0.92 0.95 0.98 rg {$x0} ".($top-$hh)." ".($x6-$x0)." {$hh} re f";$ops[]="0 0 0 RG 0 0 0 rg";$rect($x0,$top-$hh,$x6-$x0,$hh);$txt('Product',$x0+6,$top-16,8,true);$txt('Qty',$x1+7,$top-16,8,true);$txt('Price',$x2+7,$top-16,8,true);$txt('GST',$x3+7,$top-16,8,true);$txt('Tax',$x4+7,$top-16,8,true);$txt('Total',$x5+7,$top-16,8,true);$rect($x0,$bottom,$x6-$x0,$top-$bottom);
        foreach([$x1,$x2,$x3,$x4,$x5] as $vx)$ln($vx,$bottom,$vx,$top);
        $rowY=$top-$hh;
        foreach($chunk as $item){$rowY-=$rh;$name=trim((string)($item['product_name']??'Product'));$size=trim((string)($item['size']??''));if($size!=='')$name.=' ('.$size.')';$nl=dw_pdf_wrap($name,30);$txt(substr($nl[0],0,34),$x0+5,$rowY+8,7.5);$txt(number_format((float)$item['quantity'],2),$x1+7,$rowY+8,7.5);$txt(number_format((float)$item['unit_price'],2),$x2+7,$rowY+8,7.5);$txt(number_format((float)$item['tax_percent'],2).'%', $x3+7,$rowY+8,7.5);$txt(number_format((float)$item['tax_amount'],2),$x4+7,$rowY+8,7.5);$txt(number_format((float)$item['total_amount'],2),$x5+7,$rowY+8,7.5);}
        $y=$bottom-25;$pageTax=array_sum(array_map(fn($i)=>(float)($i['tax_amount']??0),$chunk));$pageTaxable=array_sum(array_map(fn($i)=>(float)($i['total_amount']??0)-(float)($i['tax_amount']??0),$chunk));$txt('Taxable Subtotal:',370,$y,9,true);$txt('INR '.number_format($pageTaxable,2),485,$y,9);$y-=15;
        if($pageIndex===count($chunks)-1){$txt('GST Total:',370,$y,9,true);$txt('INR '.number_format(array_sum(array_map(fn($i)=>(float)($i['tax_amount']??0),$itemData)),2),485,$y,9);$y-=17;$ops[]="0.93 0.95 1 rg 360 ".($y-6)." 195 25 re f";$ops[]="0 0 0 rg";$rect(360,$y-6,195,25);$txt('GRAND TOTAL:',372,$y+3,10,true);$txt('INR '.number_format($grandTotal,2),475,$y+3,10,true);$y-=25;$txt('Paid Amount:',370,$y,9,true);$txt('INR '.number_format($paidAmount,2),485,$y,9);$y-=15;$txt('Balance Due:',370,$y,9,true);$txt('INR '.number_format($balanceAmount,2),485,$y,9);$y-=28;$status=$balanceAmount<=0?'PAID':($paidAmount>0?'PARTIAL':'UNPAID');$txt('Payment Status: '.$status,40,$y,10,true);$y-=30;$txt('Thank you for your business.',40,$y,9,true);$txt('This is a computer-generated invoice.',40,$y-14,8);}else{$txt('Continued on next page...',40,$y,8);}
        $streams[]=implode("\n",$ops)."\n";
    }
    $objects=[];$objects[]="<< /Type /Catalog /Pages 2 0 R >>";$kids=[];$pageCount=count($streams);for($i=0;$i<$pageCount;$i++)$kids[]=(3+$i*2)." 0 R";$objects[]="<< /Type /Pages /Kids [".implode(' ',$kids)."] /Count {$pageCount} >>";
    foreach($streams as $i=>$stream){$p=3+$i*2;$c=$p+1;$objects[]="<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {$W} {$H}] /Resources << /Font << /F1 ".($pageCount*2+3)." 0 R /F2 ".($pageCount*2+4)." 0 R >> >> /Contents {$c} 0 R >>";$objects[]="<< /Length ".strlen($stream)." >>\nstream\n{$stream}endstream";}
    $objects[]="<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>";$objects[]="<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>";$pdf="%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";$offsets=[0];foreach($objects as $n=>$obj){$num=$n+1;$offsets[$num]=strlen($pdf);$pdf.="{$num} 0 obj\n{$obj}\nendobj\n";}$xref=strlen($pdf);$pdf.="xref\n0 ".(count($objects)+1)."\n0000000000 65535 f \n";for($i=1;$i<=count($objects);$i++)$pdf.=sprintf("%010d 00000 n \n",$offsets[$i]);$pdf.="trailer\n<< /Size ".(count($objects)+1)." /Root 1 0 R >>\nstartxref\n{$xref}\n%%EOF";
    $safe=preg_replace('/[^A-Za-z0-9._-]+/','_',$invoiceNo);$path=rtrim(sys_get_temp_dir(),DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.'invoice_'.$safe.'_'.$saleId.'.pdf';if(file_put_contents($path,$pdf)===false)throw new RuntimeException('Unable to create invoice PDF attachment.');return $path;
}

function dw_send_invoice_email(PDO $pdo,int $saleId,string $invoiceNo,string $saleDate,array $itemData,float $grandTotal,float $paidAmount,float $balanceAmount,array $customerInfo):array{
    $result=['sent'=>false,'message'=>'','pdf'=>''];
    $email=trim((string)($customerInfo['email']??''));
    $customerName=trim((string)($customerInfo['name']??'Customer'));

    if($email==='' || !filter_var($email,FILTER_VALIDATE_EMAIL)){
        $result['message']='Customer email is missing or invalid.';
        return $result;
    }

    $autoload=__DIR__.'/vendor/autoload.php';
    if(!is_file($autoload)){
        $result['message']='PHPMailer is not installed. Upload vendor/autoload.php.';
        return $result;
    }

    require_once $autoload;
    if(!class_exists('PHPMailer\PHPMailer\PHPMailer')){
        $result['message']='PHPMailer class was not found in vendor/autoload.php.';
        return $result;
    }

    try{
        $settings=[];
        try{
            $st=$pdo->query("SELECT * FROM settings LIMIT 1");
            $settings=$st?($st->fetch(PDO::FETCH_ASSOC)?:[]):[];
        }catch(Throwable $e){}

        $shop=trim((string)($settings['shop_name']??'DUBAI WHEELS'));
        if($shop==='')$shop='DUBAI WHEELS';
        $reply=trim((string)($settings['shop_email']??'sales@dubaiwheels.xyz'));
        if(!filter_var($reply,FILTER_VALIDATE_EMAIL))$reply='sales@dubaiwheels.xyz';

        $rows='';
        $plainRows='';
        $taxableTotal=0.00;
        $gstTotal=0.00;

        foreach($itemData as $itm){
            $product=(string)($itm['product_name']??'Product');
            $size=trim((string)($itm['size']??''));
            if($size!=='')$product.=' ('.$size.')';
            $qty=(float)($itm['quantity']??0);
            $price=(float)($itm['unit_price']??0);
            $gst=(float)($itm['tax_percent']??0);
            $tax=(float)($itm['tax_amount']??0);
            $total=(float)($itm['total_amount']??0);
            $taxableTotal+=($total-$tax);
            $gstTotal+=$tax;
            $rows.='<tr>
                <td style="padding:8px;border:1px solid #e2e8f0;">'.htmlspecialchars($product,ENT_QUOTES,'UTF-8').'</td>
                <td style="padding:8px;border:1px solid #e2e8f0;text-align:center;">'.number_format($qty,2).'</td>
                <td style="padding:8px;border:1px solid #e2e8f0;text-align:right;">INR '.number_format($price,2).'</td>
                <td style="padding:8px;border:1px solid #e2e8f0;text-align:center;">'.number_format($gst,2).'%</td>
                <td style="padding:8px;border:1px solid #e2e8f0;text-align:right;">INR '.number_format($tax,2).'</td>
                <td style="padding:8px;border:1px solid #e2e8f0;text-align:right;font-weight:700;">INR '.number_format($total,2).'</td>
            </tr>';
            $plainRows.=$product.' | Qty: '.number_format($qty,2).' | Price: INR '.number_format($price,2).' | GST: '.number_format($gst,2).'% | Tax: INR '.number_format($tax,2).' | Total: INR '.number_format($total,2)."\n";
        }

        $status=$balanceAmount<=0?'PAID':($paidAmount>0?'PARTIAL':'UNPAID');
        $body='<div style="font-family:Arial,sans-serif;background:#f5f7fb;padding:24px;">
          <div style="max-width:820px;margin:auto;background:#fff;border:1px solid #e2e8f0;border-radius:14px;overflow:hidden;color:#1e293b;">
            <div style="background:linear-gradient(135deg,#4f46e5,#2563eb);color:#fff;padding:22px 24px;">
              <div style="font-size:21px;font-weight:800;">'.htmlspecialchars($shop,ENT_QUOTES,'UTF-8').'</div>
              <div style="margin-top:4px;">Invoice Details</div>
            </div>
            <div style="padding:24px;">
              <table style="width:100%;border-collapse:collapse;margin-bottom:18px;"><tr>
                <td><strong>Invoice No:</strong> '.htmlspecialchars($invoiceNo,ENT_QUOTES,'UTF-8').'</td>
                <td style="text-align:right"><strong>Date:</strong> '.htmlspecialchars($saleDate,ENT_QUOTES,'UTF-8').'</td>
              </tr><tr>
                <td><strong>Customer:</strong> '.htmlspecialchars($customerName,ENT_QUOTES,'UTF-8').'</td>
                <td style="text-align:right"><strong>Status:</strong> '.$status.'</td>
              </tr></table>
              <p>Dear <strong>'.htmlspecialchars($customerName,ENT_QUOTES,'UTF-8').'</strong>,</p>
              <p>Thank you for your purchase. Please find your complete invoice details below.</p>
              <table style="width:100%;border-collapse:collapse;font-size:13px;">
                <thead><tr style="background:#eef2ff;">
                  <th style="padding:8px;border:1px solid #c7d2fe;text-align:left;">Product</th>
                  <th style="padding:8px;border:1px solid #c7d2fe;">Qty</th>
                  <th style="padding:8px;border:1px solid #c7d2fe;text-align:right;">Price</th>
                  <th style="padding:8px;border:1px solid #c7d2fe;">GST</th>
                  <th style="padding:8px;border:1px solid #c7d2fe;text-align:right;">Tax</th>
                  <th style="padding:8px;border:1px solid #c7d2fe;text-align:right;">Total</th>
                </tr></thead><tbody>'.$rows.'</tbody>
              </table>
              <div style="margin-top:18px;text-align:right;line-height:1.9;">
                Taxable Subtotal: <strong>INR '.number_format($taxableTotal,2).'</strong><br>
                GST Total: <strong>INR '.number_format($gstTotal,2).'</strong><br>
                <span style="font-size:18px;color:#2563eb;">Grand Total: <strong>INR '.number_format($grandTotal,2).'</strong></span><br>
                Paid Amount: <strong>INR '.number_format($paidAmount,2).'</strong><br>
                Balance Due: <strong>INR '.number_format($balanceAmount,2).'</strong><br>
                Payment Status: <strong>'.$status.'</strong>
              </div>
              <hr style="border:0;border-top:1px solid #e2e8f0;margin:22px 0;">
              <div style="font-size:12px;color:#64748b;">This email contains invoice details only. No PDF attachment is included.</div>
            </div>
          </div></div>';

        $alt='Invoice Details - '.$invoiceNo."\n".
             'Date: '.$saleDate."\n".
             'Customer: '.$customerName."\n\n".
             'ITEMS\n'.$plainRows."\n".
             'Taxable Subtotal: INR '.number_format($taxableTotal,2)."\n".
             'GST Total: INR '.number_format($gstTotal,2)."\n".
             'Grand Total: INR '.number_format($grandTotal,2)."\n".
             'Paid Amount: INR '.number_format($paidAmount,2)."\n".
             'Balance Due: INR '.number_format($balanceAmount,2)."\n".
             'Payment Status: '.$status;

        $mail=new PHPMailer\PHPMailer\PHPMailer(true);
        $mail->isSMTP();
        $mail->Host='mail.dubaiwheels.xyz';
        $mail->SMTPAuth=true;
        $mail->Username='sales@dubaiwheels.xyz';
        $mail->Password='MAMMAPAPPA@05#';
        $mail->Port=465;
        $mail->SMTPSecure=PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
        $mail->SMTPAutoTLS=false;
        $mail->CharSet='UTF-8';
        $mail->Timeout=30;
        $mail->SMTPDebug=0;
        $mail->Debugoutput=function($str,$level){ error_log('PHPMailer: '.trim((string)$str)); };
        $mail->SMTPOptions=array('ssl'=>array('verify_peer'=>false,'verify_peer_name'=>false,'allow_self_signed'=>true));
        $mail->setFrom('sales@dubaiwheels.xyz',$shop);
        $mail->addReplyTo($reply,$shop);
        $mail->addAddress($email,$customerName);
        $mail->isHTML(true);
        $mail->Subject='Invoice Details - '.$invoiceNo.' - '.$shop;
        $mail->Body=$body;
        $mail->AltBody=$alt;
        // Intentionally NO PDF generation and NO addAttachment().
        $mail->send();

        $result['sent']=true;
        $result['message']='Invoice details emailed successfully.';
        return $result;
    }catch(Throwable $e){
        error_log('Invoice email failed: '.$e->getMessage());
        if(isset($mail) && $mail instanceof PHPMailer\PHPMailer\PHPMailer){
            error_log('PHPMailer ErrorInfo: '.$mail->ErrorInfo);
        }
        $result['message']='Invoice saved. Invoice details email could not be sent.';
        return $result;
    }
}

// Ensure necessary sales tables exist dynamically if not present
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `sales` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `invoice_no` varchar(50) NOT NULL,
        `customer_id` int(11) NOT NULL,
        `sale_date` date NOT NULL,
        `subtotal` decimal(12,2) DEFAULT 0.00,
        `tax_amount` decimal(12,2) DEFAULT 0.00,
        `total_amount` decimal(12,2) DEFAULT 0.00,
        `paid_amount` decimal(12,2) DEFAULT 0.00,
        `balance_amount` decimal(12,2) DEFAULT 0.00,
        `payment_status` varchar(50) DEFAULT 'Paid',
        `user_id` int(11) DEFAULT 1,
        `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;");

    $pdo->exec("CREATE TABLE IF NOT EXISTS `sale_items` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `sale_id` int(11) NOT NULL,
        `product_id` int(11) NOT NULL,
        `quantity` decimal(10,2) NOT NULL,
        `unit_price` decimal(10,2) NOT NULL,
        `tax_percent` decimal(5,2) DEFAULT 0.00,
        `tax_amount` decimal(12,2) DEFAULT 0.00,
        `total_amount` decimal(12,2) DEFAULT 0.00,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;");
} catch (\Exception $e) {}

// Fetch Global Tax Percentage from settings table dynamically
$global_tax_percent = 0.00;
try {
    $stmt_set = $pdo->query("SELECT tax_percentage FROM settings LIMIT 1");
    if ($set_row = $stmt_set->fetch()) {
        $global_tax_percent = floatval($set_row['tax_percentage']);
    }
} catch (\Exception $e) {}

$success_msg = '';
$error_msg = '';

// Handle Delete Sale
if (isset($_GET['delete_id'])) {
    $del_id = intval($_GET['delete_id']);

    try {
        $pdo->beginTransaction();

        $stmt_items = $pdo->prepare("SELECT product_id, quantity FROM sale_items WHERE sale_id = ?");
        $stmt_items->execute([$del_id]);
        $items_to_restore = $stmt_items->fetchAll();

        foreach ($items_to_restore as $it) {
            $stmt_rst = $pdo->prepare("UPDATE products SET stock = stock + ? WHERE id = ?");
            $stmt_rst->execute([$it['quantity'], $it['product_id']]);
        }

        $pdo->prepare("DELETE FROM sale_items WHERE sale_id = ?")->execute([$del_id]);
        $pdo->prepare("DELETE FROM sales WHERE id = ?")->execute([$del_id]);

        $pdo->commit();
        $success_msg = "Sale invoice successfully deleted and stock restored.";
    } catch (Exception $e) {
        $pdo->rollBack();
        $error_msg = "Error deleting sale: " . $e->getMessage();
    }
}

// Handle POS form submission (New Sale or Edit Existing Sale)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['save_sale']) || isset($_POST['update_sale']))) {
    $edit_sale_id = intval($_POST['edit_sale_id'] ?? 0);
    $customer_id  = intval($_POST['customer_id'] ?? 0);
    $sale_date    = $_POST['sale_date'] ?? date('Y-m-d');
    $paid_amount  = floatval($_POST['paid_amount'] ?? 0);
    $products_arr = $_POST['product_id'] ?? [];
    $qtys_arr     = $_POST['quantity'] ?? [];
    $prices_arr   = $_POST['unit_price'] ?? []; 
    $gst_arr      = $_POST['gst_percent'] ?? [];

    if ($customer_id <= 0) {
        $error_msg = "Please select a valid customer.";
    } elseif (empty($products_arr)) {
        $error_msg = "Please add at least one product to the sale invoice.";
    } else {
        try {
            $pdo->beginTransaction();

            if ($edit_sale_id > 0) {
                $stmt_old_items = $pdo->prepare("SELECT product_id, quantity FROM sale_items WHERE sale_id = ?");
                $stmt_old_items->execute([$edit_sale_id]);
                $old_items = $stmt_old_items->fetchAll();

                foreach ($old_items as $oit) {
                    $stmt_rst_old = $pdo->prepare("UPDATE products SET stock = stock + ? WHERE id = ?");
                    $stmt_rst_old->execute([$oit['quantity'], $oit['product_id']]);
                }

                $pdo->prepare("DELETE FROM sale_items WHERE sale_id = ?")->execute([$edit_sale_id]);
            }

            $subtotal_sum = 0;
            $tax_sum = 0;
            $grand_total = 0;
            $item_data = [];

            for ($i = 0; $i < count($products_arr); $i++) {
                $pid = intval($products_arr[$i]);
                $qty = floatval($qtys_arr[$i]);
                $inclusive_price = floatval($prices_arr[$i]); 
                $tax_percent = isset($gst_arr[$i]) && $gst_arr[$i] !== '' ? floatval($gst_arr[$i]) : $global_tax_percent;

                if ($pid <= 0 || $qty <= 0) continue;

                $stmt_stk = $pdo->prepare("SELECT stock, product_name, brand_name, size FROM products WHERE id = ?");
                $stmt_stk->execute([$pid]);
                $prod_info = $stmt_stk->fetch();

                if (!$prod_info) {
                    throw new Exception("Product ID $pid not found.");
                }
                if ($prod_info['stock'] < $qty) {
                    throw new Exception("Insufficient stock for product: " . $prod_info['product_name'] . " (Available: " . $prod_info['stock'] . ")");
                }

                $line_gross_total = $qty * $inclusive_price;
                
                if ($tax_percent > 0) {
                    $line_subtotal = $line_gross_total / (1 + ($tax_percent / 100));
                    $line_tax = $line_gross_total - $line_subtotal;
                } else {
                    $line_subtotal = $line_gross_total;
                    $line_tax = 0.00;
                }

                $subtotal_sum += $line_subtotal;
                $tax_sum += $line_tax;
                $grand_total += $line_gross_total;

                $item_data[] = [
                    'product_id'   => $pid,
                    'product_name' => $prod_info['product_name'],
                    'brand_name'   => $prod_info['brand_name'],
                    'size'         => $prod_info['size'],
                    'quantity'     => $qty,
                    'unit_price'   => $inclusive_price, 
                    'tax_percent'  => $tax_percent,
                    'tax_amount'   => $line_tax,
                    'total_amount' => $line_gross_total
                ];
            }

            if (empty($item_data)) {
                throw new Exception("No valid items selected for invoicing.");
            }

            $balance_amount = $grand_total - $paid_amount;
            if ($balance_amount < 0) $balance_amount = 0;
            $payment_status = ($balance_amount <= 0) ? 'Paid' : (($paid_amount > 0) ? 'Partial' : 'Unpaid');

            if ($edit_sale_id > 0) {
                $stmt_update = $pdo->prepare("UPDATE sales SET customer_id = ?, sale_date = ?, subtotal = ?, tax_amount = ?, total_amount = ?, paid_amount = ?, balance_amount = ?, payment_status = ? WHERE id = ?");
                $stmt_update->execute([$customer_id, $sale_date, $subtotal_sum, $tax_sum, $grand_total, $paid_amount, $balance_amount, $payment_status, $edit_sale_id]);
                $sale_id = $edit_sale_id;
            } else {
                $invoice_no = 'INV-S-' . strtoupper(substr(uniqid(), -6));
                $stmt_sale = $pdo->prepare("INSERT INTO sales (invoice_no, customer_id, sale_date, subtotal, tax_amount, total_amount, paid_amount, balance_amount, payment_status, user_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt_sale->execute([$invoice_no, $customer_id, $sale_date, $subtotal_sum, $tax_sum, $grand_total, $paid_amount, $balance_amount, $payment_status, $_SESSION['user_id'] ?? 1]);
                $sale_id = $pdo->lastInsertId();
            }

            foreach ($item_data as $item) {
                $stmt_item = $pdo->prepare("INSERT INTO sale_items (sale_id, product_id, quantity, unit_price, tax_percent, tax_amount, total_amount) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt_item->execute([$sale_id, $item['product_id'], $item['quantity'], $item['unit_price'], $item['tax_percent'], $item['tax_amount'], $item['total_amount']]);

                $stmt_upd_stk = $pdo->prepare("UPDATE products SET stock = stock - ? WHERE id = ?");
                $stmt_upd_stk->execute([$item['quantity'], $item['product_id']]);
            }

            $pdo->commit();

            // SEND INVOICE DETAILS BY EMAIL - NO PDF ATTACHMENT
            $email_result = ['sent'=>false,'message'=>'Customer email not available.','pdf'=>''];
            try {
                $stmt_cust = $pdo->prepare("SELECT name, email FROM customers WHERE id = ?");
                $stmt_cust->execute([$customer_id]);
                $customer_info = $stmt_cust->fetch(PDO::FETCH_ASSOC);
                if ($customer_info) {
                    $email_result = dw_send_invoice_email(
                        $pdo,
                        (int)$sale_id,
                        (string)($invoice_no ?? ('INV-S-'.$sale_id)),
                        (string)$sale_date,
                        $item_data,
                        (float)$grand_total,
                        (float)$paid_amount,
                        (float)$balance_amount,
                        $customer_info
                    );
                }
            } catch (Throwable $mail_err) {
                $email_result['message'] = 'Invoice email failed: ' . $mail_err->getMessage();
                error_log($email_result['message']);
            }
            $email_status = !empty($email_result['sent']) ? 'sent' : 'failed';

            // Keep the original redirect/automatic print behavior.
            $pos_page = basename($_SERVER['PHP_SELF']);
            $redirect = $pos_page . '?auto_print=' . (int)$sale_id . '&email_status=' . urlencode($email_status);
            if (!headers_sent()) {
                header('Location: ' . $redirect);
                exit();
            }
            echo '<script>location.href=' . json_encode($redirect) . ';</script>';
            exit();
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_msg = "Error processing sale: " . $e->getMessage();
        }
    }
}

// Fetch active customers
try {
    $customers = $pdo->query("SELECT id, name, phone FROM customers ORDER BY name ASC")->fetchAll();
} catch (\Exception $e) {
    $customers = [];
}

// Fetch active products with stock
try {
    $products = $pdo->query("SELECT id, product_name, brand_name, size, price, stock FROM products WHERE stock > 0 ORDER BY product_name ASC")->fetchAll();
} catch (\Exception $e) {
    $products = [];
}

// Check if we are currently editing a sale
$edit_mode = false;
$edit_sale = null;
$edit_sale_items = [];
if (isset($_GET['edit_id']) && intval($_GET['edit_id']) > 0) {
    $edit_id = intval($_GET['edit_id']);
    try {
        $stmt_es = $pdo->prepare("SELECT * FROM sales WHERE id = ?");
        $stmt_es->execute([$edit_id]);
        $edit_sale = $stmt_es->fetch();
        if ($edit_sale) {
            $edit_mode = true;
            $stmt_esi = $pdo->prepare("SELECT * FROM sale_items WHERE sale_id = ?");
            $stmt_esi->execute([$edit_id]);
            $edit_sale_items = $stmt_esi->fetchAll();
        }
    } catch (\Exception $e) {}
}

// Fetch TODAY'S sales list only
try {
    $recent_sales = $pdo->query("
        SELECT s.*, c.name as customer_name, c.phone as customer_phone, c.address as customer_address 
        FROM sales s 
        LEFT JOIN customers c ON s.customer_id = c.id 
        WHERE s.sale_date = CURDATE()
        ORDER BY s.id DESC
    ")->fetchAll();
} catch (\Exception $e) {
    $recent_sales = [];
}

$today_invoice_count = count($recent_sales);
$today_subtotal = 0.00;
$today_tax = 0.00;
$today_total = 0.00;
$today_paid = 0.00;
$today_balance = 0.00;
foreach ($recent_sales as $rs) {
    $today_subtotal += (float)($rs['subtotal'] ?? 0);
    $today_tax += (float)($rs['tax_amount'] ?? 0);
    $today_total += (float)($rs['total_amount'] ?? 0);
    $today_paid += (float)($rs['paid_amount'] ?? 0);
    $today_balance += (float)($rs['balance_amount'] ?? 0);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Dubai Wheels | Professional POS & Sales</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --header-height: 65px;
            --gradient-primary: linear-gradient(135deg, #4f46e5 0%, #3b82f6 100%);
            --card-border-radius: 1rem;
            --pos-primary:#4f46e5;
            --pos-primary-2:#2563eb;
            --pos-success:#059669;
            --pos-danger:#dc2626;
            --pos-warning:#d97706;
            --pos-dark:#0f172a;
            --pos-text:#1e293b;
            --pos-muted:#64748b;
            --pos-border:#e2e8f0;
            --pos-bg:#f5f7fb;
            --pos-card:#ffffff;
            --pos-radius:18px;
            --pos-shadow:0 10px 30px rgba(15,23,42,.07);
            --pos-shadow-hover:0 18px 45px rgba(15,23,42,.11);
        }
        body {
            background:
                radial-gradient(circle at 100% 0%,rgba(79,70,229,.055),transparent 28%),
                linear-gradient(180deg,#f8fafc 0%,#f3f6fb 100%) !important;
            font-family: 'Inter', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            color: var(--pos-text);
            overflow-x: hidden;
        }
        .top-navbar {
            height: 68px !important;
            background: rgba(255,255,255,.94) !important;
            border-bottom: 1px solid #e5e7eb !important;
            position: fixed;
            top: 0; right: 0; left: 0;
            z-index: 1030;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 22px !important;
            box-shadow: 0 5px 22px rgba(15,23,42,.06) !important;
            backdrop-filter: blur(14px);
        }
        .main-content {
            margin-top: 68px !important;
            padding: 25px !important;
            min-height: calc(100vh - 68px);
        }
        @media (min-width: 1200px) {
            .main-content { padding: 30px 34px !important; }
        }
        .card {
            border: 1px solid rgba(226,232,240,.92) !important;
            border-radius: var(--pos-radius) !important;
            box-shadow: var(--pos-shadow) !important;
            overflow: hidden;
            background: #fff;
        }
        .card:hover { box-shadow: var(--pos-shadow-hover) !important; }
        .card-header-gradient {
            background: radial-gradient(circle at 90% 20%,rgba(255,255,255,.16),transparent 22%), linear-gradient(135deg,#4338ca 0%,#2563eb 100%) !important;
            color: #ffffff;
            padding: 17px 21px !important;
            border: 0 !important;
        }
        .summary-card {
            background: radial-gradient(circle at 100% 0%,rgba(99,102,241,.08),transparent 30%), linear-gradient(145deg,#fff,#f8fafc) !important;
            border: 1px solid #dfe5ed !important;
            border-radius: 15px !important;
            box-shadow: 0 9px 24px rgba(15,23,42,.06) !important;
        }
        .btn-primary {
            background: var(--gradient-primary);
            border: none;
            box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
            transition: all 0.2s ease;
        }
        .btn-primary:hover {
            background: linear-gradient(135deg, #4338ca 0%, #2563eb 100%);
            transform: translateY(-1px);
            box-shadow: 0 6px 15px rgba(79, 70, 229, 0.4);
        }
        .form-label {
            color: #475569 !important;
            margin-bottom: 6px !important;
            font-weight: 750 !important;
        }
        .form-control, .form-select {
            min-height: 43px;
            border: 1px solid #dbe2ea !important;
            border-radius: 10px !important;
            background: #fff !important;
            color: #0f172a !important;
            box-shadow: 0 2px 6px rgba(15,23,42,.025) !important;
        }
        .form-control:focus, .form-select:focus {
            border-color: #818cf8 !important;
            box-shadow: 0 0 0 3px rgba(99,102,241,.12) !important;
        }
        #invoiceTable {
            min-width: 1120px;
            border-color: #e2e8f0 !important;
            border-radius: 12px;
            overflow: hidden;
        }
        #invoiceTable thead th {
            background: linear-gradient(180deg,#eef2ff,#e0e7ff) !important;
            color: #3730a3 !important;
            border-color: #c7d2fe !important;
            font-size: .72rem !important;
            font-weight: 800 !important;
            padding: 12px 9px !important;
            white-space: nowrap;
        }
        #invoiceTable tbody td {
            padding: 9px 7px !important;
            border-color: #edf1f5 !important;
            background: #fff;
        }
        #invoiceTable .form-control, #invoiceTable .form-select {
            min-height: 39px;
            font-size: .82rem;
            padding: .42rem .55rem;
        }
        .gst-input { color: #4338ca !important; background: #eef2ff !important; }
        .row-total { color: #1d4ed8 !important; font-weight: 800 !important; }
        .pos-page-title { display: flex; align-items: center; gap: 12px; }
        .pos-title-icon { width: 46px; height: 46px; display: flex; align-items: center; justify-content: center; border-radius: 14px; color: #fff; background: linear-gradient(135deg,#4f46e5,#2563eb); box-shadow: 0 10px 24px rgba(79,70,229,.24); }
        .pos-subtitle { color: #64748b; font-size: 11px; line-height: 1.5; }
        .pos-stat-grid { display: grid; grid-template-columns: repeat(4,minmax(0,1fr)); gap: 12px; margin-bottom: 18px; }
        .pos-stat { position: relative; overflow: hidden; padding: 15px 16px; border: 1px solid #e2e8f0; border-radius: 16px; background: rgba(255,255,255,.92); box-shadow: 0 8px 25px rgba(15,23,42,.055); }
        .pos-stat .icon { width: 38px; height: 38px; border-radius: 11px; display: flex; align-items: center; justify-content: center; margin-bottom: 10px; background: #eef2ff; color: #4f46e5; }
        .pos-stat.success .icon { background: #ecfdf5; color: #059669; } 
        .pos-stat.warning .icon { background: #fffbeb; color: #d97706; } 
        .pos-stat.danger .icon { background: #fff1f2; color: #dc2626; }
        .pos-stat small { display: block; color: #94a3b8; font-size: 8px; font-weight: 900; text-transform: uppercase; letter-spacing: .08em; }
        .pos-stat strong { display: block; margin-top: 3px; color: #0f172a; font-size: 19px; font-weight: 900; }
        .pos-stat p { margin: 3px 0 0; color: #64748b; font-size: 9px; }
        .ledger-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
        .ledger-search { max-width: 290px; min-height: 38px; border: 1px solid #dbe3ef; border-radius: 10px; padding: 0 12px 0 35px; font-size: 11px; background: #fff; }
        .ledger-search-wrap { position: relative; } 
        .ledger-search-wrap i { position: absolute; left: 12px; top: 12px; color: #94a3b8; font-size: 11px; z-index: 2; }
        .auto-print-toast {
            position: fixed; top: 22px; right: 22px; z-index: 1085;
            width: min(390px,calc(100vw - 28px)); padding: 15px 16px;
            display: flex; align-items: center; gap: 12px;
            border: 1px solid #c7d2fe; border-radius: 15px; background: rgba(255,255,255,.97);
            box-shadow: 0 18px 45px rgba(15,23,42,.18);
        }
        @media(max-width:991.98px) { .pos-stat-grid { grid-template-columns: repeat(2,minmax(0,1fr)); } }
    </style>
</head>
<body>
<?php if (isset($_GET['auto_print']) && (int)$_GET['auto_print'] > 0): ?>
<div class="auto-print-toast" id="autoPrintToast">
    <div class="toast-icon" style="width:42px;height:42px;display:flex;align-items:center;justify-content:center;border-radius:12px;color:#4338ca;background:#eef2ff;"><i class="fa-solid fa-print"></i></div>
    <div>
        <strong>Transaction saved successfully</strong>
        <span id="emailStatusText">Opening invoice print window automatically…</span>
    </div>
    <button type="button" class="toast-close ms-auto border-0 bg-transparent text-muted" onclick="document.getElementById('autoPrintToast').remove()"><i class="fa-solid fa-xmark"></i></button>
</div>
<?php endif; ?>

    <!-- Top Navigation Header -->
    <header class="top-navbar">
        <div class="d-flex align-items-center">
            <a class="navbar-brand fw-bold text-dark text-decoration-none d-flex align-items-center" href="admindashboard.php">
                <div class="text-white p-2 rounded-3 d-flex align-items-center justify-content-center me-2 shadow-sm" style="width: 38px; height: 38px; background: var(--gradient-primary);">
                    <i class="fa-solid fa-dharmachakra fa-spin" style="animation-duration: 15s;"></i>
                </div>
                <span class="fs-6 fs-sm-5">DUBAI <span style="color: #4f46e5;">WHEELS</span></span>
            </a>
        </div>
        <div class="d-flex align-items-center gap-2">
            <button type="button" class="btn btn-outline-primary btn-sm rounded-pill px-3 py-1 d-flex align-items-center gap-2 shadow-sm" id="fullscreenToggleBtn" onclick="toggleFullScreen()" title="Toggle Fullscreen">
                <i class="fa-solid fa-expand" id="fullscreenIcon"></i>
                <span class="d-none md-inline small fw-semibold">Fullscreen</span>
            </button>
            <div class="dropdown">
                <a href="#" class="d-flex align-items-center text-dark text-decoration-none dropdown-toggle py-1 px-2 rounded-pill border bg-light shadow-sm" data-bs-toggle="dropdown">
                    <div class="text-white rounded-circle d-flex align-items-center justify-content-center me-sm-2 shadow-sm" style="width: 32px; height: 32px; font-weight: 600; font-size: 0.85rem; background: var(--gradient-primary);">
                        <?php echo strtoupper(substr($_SESSION['username'] ?? 'A', 0, 1)); ?>
                    </div>
                    <span class="d-none d-sm-inline fw-semibold small me-1"><?php echo htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?></span>
                </a>
                <ul class="dropdown-menu dropdown-menu-end shadow-lg border-0 mt-2 py-2 rounded-3">
                    <li><a class="dropdown-item py-2 px-3 small text-danger fw-medium" href="logout.php"><i class="fa-solid fa-right-from-bracket me-2"></i>Sign Out</a></li>
                </ul>
            </div>
        </div>
    </header>

    <!-- Main Content Area -->
    <main class="main-content">
        <div class="container-fluid px-0">
            
            <div class="d-flex flex-wrap justify-content-between align-items-center mb-3 gap-3">
                <div class="pos-page-title">
                    <div class="pos-title-icon"><i class="fa-solid fa-cash-register"></i></div>
                    <div>
                        <h2 class="h4 h3-md fw-bold text-dark mb-1"><?php echo $edit_mode ? 'Edit Sales Invoice #' . htmlspecialchars($edit_sale['invoice_no']) : 'Sales & Point of Sale'; ?></h2>
                        <p class="pos-subtitle mb-0">Professional counter billing with automatic or manual GST, stock validation, and invoice editing options.</p>
                    </div>
                </div>
                <div class="d-flex align-items-center gap-2">
                    <?php if ($edit_mode): ?>
                        <a href="<?php echo basename($_SERVER['PHP_SELF']); ?>" class="btn btn-outline-secondary btn-sm shadow-sm"><i class="fa-solid fa-arrow-left me-1"></i> Cancel Editing</a>
                    <?php endif; ?>
                    <span class="badge rounded-pill bg-white text-secondary border px-3 py-2 shadow-sm"><i class="fa-regular fa-calendar me-1"></i><?php echo date('d M Y'); ?></span>
                    <span class="badge rounded-pill bg-success-subtle text-success border border-success-subtle px-3 py-2"><i class="fa-solid fa-circle me-1 small"></i>POS ONLINE</span>
                </div>
            </div>

            <div class="pos-stat-grid">
                <div class="pos-stat"><div class="icon"><i class="fa-solid fa-file-invoice"></i></div><small>Today's Invoices</small><strong><?php echo number_format($today_invoice_count); ?></strong><p>Completed transactions</p></div>
                <div class="pos-stat success"><div class="icon"><i class="fa-solid fa-arrow-trend-up"></i></div><small>Total Sales</small><strong>₹<?php echo number_format($today_total,2); ?></strong><p>Gross invoice value</p></div>
                <div class="pos-stat warning"><div class="icon"><i class="fa-solid fa-wallet"></i></div><small>Collected</small><strong>₹<?php echo number_format($today_paid,2); ?></strong><p>Amount received</p></div>
                <div class="pos-stat danger"><div class="icon"><i class="fa-solid fa-clock"></i></div><small>Balance Due</small><strong>₹<?php echo number_format($today_balance,2); ?></strong><p>Outstanding amount</p></div>
            </div>

            <?php if(!empty($success_msg)): ?>
                <div class="alert alert-success alert-dismissible fade show border-0 shadow-sm mb-4 rounded-3 text-white" role="alert" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;">
                    <i class="fa-solid fa-circle-check me-2"></i> <?php echo $success_msg; ?>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <?php if(!empty($error_msg)): ?>
                <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm mb-4 rounded-3 text-white" role="alert" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%) !important;">
                    <i class="fa-solid fa-triangle-exclamation me-2"></i> <?php echo $error_msg; ?>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <!-- POS / Edit Invoice Form Panel -->
            <div class="card shadow-sm mb-4 mb-md-5">
                <div class="card-header card-header-gradient d-flex align-items-center justify-content-between">
                    <h5 class="card-title fw-bold mb-0 text-white fs-5"><i class="fa-solid <?php echo $edit_mode ? 'fa-pen-to-square' : 'fa-cart-plus'; ?> me-2"></i><?php echo $edit_mode ? 'Modify Invoice Data' : 'New Counter Sales Invoice'; ?></h5>
                    <span class="badge bg-white text-primary px-3 py-1 rounded-pill fw-semibold shadow-sm"><?php echo $edit_mode ? 'Edit Mode Active' : 'Auto / Manual GST Mode'; ?></span>
                </div>
                <div class="card-body p-3 p-md-4">
                    <form method="POST" id="posForm">
                        <input type="hidden" id="defaultGstPercentage" value="<?php echo $global_tax_percent; ?>">
                        <?php if ($edit_mode): ?>
                            <input type="hidden" name="edit_sale_id" value="<?php echo $edit_sale['id']; ?>">
                        <?php endif; ?>
                        
                        <div class="row g-3 mb-4">
                            <div class="col-12 col-md-6">
                                <label class="form-label small fw-bold text-secondary">Select Customer <span class="text-danger">*</span></label>
                                <select name="customer_id" class="form-select" required>
                                    <option value="">-- Choose Customer Name --</option>
                                    <?php foreach($customers as $cust): ?>
                                        <option value="<?php echo $cust['id']; ?>" <?php echo ($edit_mode && $edit_sale['customer_id'] == $cust['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($cust['name']); ?> (<?php echo htmlspecialchars($cust['phone']); ?>)</option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-12 col-md-6">
                                <label class="form-label small fw-bold text-secondary">Sale Date <span class="text-danger">*</span></label>
                                <input type="date" name="sale_date" class="form-control" value="<?php echo $edit_mode ? $edit_sale['sale_date'] : date('Y-m-d'); ?>" required>
                            </div>
                        </div>

                        <!-- Items Table Builder -->
                        <div class="d-flex align-items-center gap-2 mb-2">
                            <span class="badge rounded-pill bg-primary bg-opacity-10 text-primary border border-primary-subtle px-3 py-2">
                                <i class="fa-solid fa-layer-group me-1"></i> Invoice Items
                            </span>
                        </div>
                        <div class="table-responsive mb-3">
                            <table class="table table-bordered align-middle mb-2 shadow-sm" id="invoiceTable">
                                <thead>
                                    <tr>
                                        <th style="width: 27%;">Product Item</th>
                                        <th style="width: 8%;">Stock</th>
                                        <th style="width: 9%;">Quantity</th>
                                        <th style="width: 11%;">Price (Incl. GST)</th>
                                        <th style="width: 9%;">GST %</th>
                                        <th style="width: 11%;">Taxable (₹)</th>
                                        <th style="width: 11%;">GST Amt (₹)</th>
                                        <th style="width: 10%;">Total (₹)</th>
                                        <th style="width: 4%;" class="text-center">Action</th>
                                    </tr>
                                </thead>
                                <tbody id="itemRows">
                                    <?php if ($edit_mode && !empty($edit_sale_items)): ?>
                                        <?php foreach ($edit_sale_items as $eitem): ?>
                                            <tr>
                                                <td>
                                                    <select name="product_id[]" class="form-select product-select border-2" required onchange="updateProductDetails(this)">
                                                        <option value="">-- Select Product --</option>
                                                        <?php foreach($products as $prod): 
                                                            $selected_attr = ($prod['id'] == $eitem['product_id']) ? 'selected' : '';
                                                        ?>
                                                            <option value="<?php echo $prod['id']; ?>" data-price="<?php echo $prod['price']; ?>" data-stock="<?php echo $prod['stock']; ?>" <?php echo $selected_attr; ?>>
                                                                <?php echo htmlspecialchars($prod['product_name']); ?> [<?php echo htmlspecialchars($prod['brand_name']); ?> - <?php echo htmlspecialchars($prod['size']); ?>]
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </td>
                                                <td><input type="text" class="form-control stock-display bg-light text-center fw-bold text-secondary" readonly value="0"></td>
                                                <td><input type="number" step="0.01" min="0.01" name="quantity[]" class="form-control qty-input border-2 text-center" value="<?php echo $eitem['quantity']; ?>" required oninput="calculateRowTotal(this)"></td>
                                                <td><input type="number" step="0.01" min="0" name="unit_price[]" class="form-control price-input border-2 text-end" value="<?php echo $eitem['unit_price']; ?>" required oninput="calculateRowTotal(this)"></td>
                                                <td><input type="number" step="0.01" min="0" max="100" name="gst_percent[]" class="form-control gst-input border-2 text-center fw-bold text-indigo" value="<?php echo $eitem['tax_percent']; ?>" required oninput="calculateRowTotal(this)"></td>
                                                <td><input type="text" class="form-control row-subtotal bg-light text-end" readonly value="0.00"></td>
                                                <td><input type="text" class="form-control row-tax bg-light text-end" readonly value="0.00"></td>
                                                <td><input type="text" class="form-control row-total bg-light text-end fw-bold text-primary" readonly value="<?php echo $eitem['total_amount']; ?>"></td>
                                                <td class="text-center">
                                                    <button type="button" class="btn btn-outline-danger btn-sm shadow-sm" onclick="removeRow(this)"><i class="fa-solid fa-trash"></i></button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td>
                                                <select name="product_id[]" class="form-select product-select border-2" required onchange="updateProductDetails(this)">
                                                    <option value="">-- Select Product --</option>
                                                    <?php foreach($products as $prod): ?>
                                                        <option value="<?php echo $prod['id']; ?>" data-price="<?php echo $prod['price']; ?>" data-stock="<?php echo $prod['stock']; ?>">
                                                            <?php echo htmlspecialchars($prod['product_name']); ?> [<?php echo htmlspecialchars($prod['brand_name']); ?> - <?php echo htmlspecialchars($prod['size']); ?>]
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </td>
                                            <td><input type="text" class="form-control stock-display bg-light text-center fw-bold text-secondary" readonly value="0"></td>
                                            <td><input type="number" step="0.01" min="0.01" name="quantity[]" class="form-control qty-input border-2 text-center" value="1" required oninput="calculateRowTotal(this)"></td>
                                            <td><input type="number" step="0.01" min="0" name="unit_price[]" class="form-control price-input border-2 text-end" value="0.00" required oninput="calculateRowTotal(this)"></td>
                                            <td><input type="number" step="0.01" min="0" max="100" name="gst_percent[]" class="form-control gst-input border-2 text-center fw-bold text-indigo" value="<?php echo $global_tax_percent; ?>" required oninput="calculateRowTotal(this)"></td>
                                            <td><input type="text" class="form-control row-subtotal bg-light text-end" readonly value="0.00"></td>
                                            <td><input type="text" class="form-control row-tax bg-light text-end" readonly value="0.00"></td>
                                            <td><input type="text" class="form-control row-total bg-light text-end fw-bold text-primary" readonly value="0.00"></td>
                                            <td class="text-center">
                                                <button type="button" class="btn btn-outline-danger btn-sm shadow-sm" onclick="removeRow(this)"><i class="fa-solid fa-trash"></i></button>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                            <button type="button" class="btn btn-outline-primary btn-sm shadow-sm mt-2 fw-semibold px-3 py-2" onclick="addRow()"><i class="fa-solid fa-plus me-1"></i> Add Another Item</button>
                        </div>

                        <!-- Summary & Payment Block -->
                        <div class="row justify-content-end mt-4">
                            <div class="col-12 col-md-5 col-lg-4">
                                <div class="summary-card p-3 p-md-4 shadow-sm">
                                    <div class="d-flex justify-content-between mb-2">
                                        <span class="text-secondary small fw-bold">Taxable Subtotal:</span>
                                        <span class="fw-bold text-dark" id="displaySubtotal">₹0.00</span>
                                    </div>
                                    <div class="d-flex justify-content-between mb-2">
                                        <span class="text-secondary small fw-bold">Total GST Amount:</span>
                                        <span class="fw-bold text-dark" id="displayTaxTotal">₹0.00</span>
                                    </div>
                                    <div class="d-flex justify-content-between mb-3 border-top border-2 pt-2">
                                        <span class="text-dark fw-bold">Grand Total:</span>
                                        <span class="fw-bold text-primary fs-4" id="displayGrandTotal">₹0.00</span>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label small fw-bold text-secondary">Paid Amount (₹)</label>
                                        <input type="number" step="0.01" min="0" name="paid_amount" id="paidAmount" class="form-control border-2 fw-bold text-success" value="<?php echo $edit_mode ? $edit_sale['paid_amount'] : '0.00'; ?>" oninput="calculateChange()">
                                    </div>
                                    <div class="d-flex justify-content-between mb-4">
                                        <span class="text-secondary small fw-bold">Balance Due:</span>
                                        <span class="fw-bold text-danger fs-5" id="displayBalance">₹0.00</span>
                                    </div>
                                    <button type="submit" name="<?php echo $edit_mode ? 'update_sale' : 'save_sale'; ?>" class="btn btn-primary w-100 shadow fw-bold py-2 fs-6">
                                        <i class="fa-solid <?php echo $edit_mode ? 'fa-pen-to-square' : 'fa-check-circle'; ?> me-2"></i> <?php echo $edit_mode ? 'Update Invoice Data' : 'Complete Sale & Email'; ?>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Today's Sales Ledger Table with Edit Option -->
            <div class="d-flex align-items-center gap-2 mb-2 px-1">
                <span class="badge rounded-pill bg-light text-primary border px-3 py-2">
                    <i class="fa-solid fa-chart-line me-1"></i> Daily Ledger
                </span>
            </div>
            <div class="card shadow-sm">
                <div class="card-header bg-white py-3 border-0">
                    <div class="ledger-toolbar">
                        <div>
                            <h5 class="card-title fw-bold mb-1 text-dark fs-5"><i class="fa-solid fa-receipt text-primary me-2"></i>Today's Sales Invoices</h5>
                            <div class="text-muted" style="font-size:9px"><?php echo date('l, d F Y'); ?> · <?php echo number_format($today_invoice_count); ?> invoice(s)</div>
                        </div>
                        <div class="ledger-search-wrap">
                            <i class="fa-solid fa-magnifying-glass"></i>
                            <input type="search" id="ledgerSearch" class="ledger-search" placeholder="Search invoice or customer..." autocomplete="off">
                        </div>
                    </div>
                </div>
                <div class="table-responsive" style="max-height: 450px; overflow-y: auto;">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light sticky-top shadow-sm" style="z-index: 1;">
                            <tr style="font-size: 0.85rem;">
                                <th>Invoice #</th>
                                <th>Date</th>
                                <th>Customer Name</th>
                                <th class="text-end">Taxable Sub (₹)</th>
                                <th class="text-end">GST Amt (₹)</th>
                                <th class="text-end">Total (₹)</th>
                                <th class="text-end">Paid (₹)</th>
                                <th class="text-end">Balance (₹)</th>
                                <th class="text-center">Status</th>
                                <th class="text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody style="font-size: 0.85rem;">
                            <?php if(count($recent_sales) > 0): ?>
                                <?php foreach($recent_sales as $sale): ?>
                                <tr class="ledger-row">
                                    <td><span class="font-monospace fw-bold text-primary"><?php echo htmlspecialchars($sale['invoice_no']); ?></span></td>
                                    <td><?php echo htmlspecialchars($sale['sale_date']); ?></td>
                                    <td class="fw-semibold"><?php echo htmlspecialchars($sale['customer_name'] ?? 'Walk-in Customer'); ?></td>
                                    <td class="text-end">₹<?php echo number_format($sale['subtotal'], 2); ?></td>
                                    <td class="text-end text-muted">₹<?php echo number_format($sale['tax_amount'], 2); ?></td>
                                    <td class="text-end fw-bold text-dark">₹<?php echo number_format($sale['total_amount'], 2); ?></td>
                                    <td class="text-end text-success fw-semibold">₹<?php echo number_format($sale['paid_amount'], 2); ?></td>
                                    <td class="text-end text-danger fw-semibold">₹<?php echo number_format($sale['balance_amount'], 2); ?></td>
                                    <td class="text-center">
                                        <?php if($sale['payment_status'] === 'Paid'): ?>
                                            <span class="badge bg-success bg-opacity-10 text-success px-2 py-1 fw-bold">Paid</span>
                                        <?php elseif($sale['payment_status'] === 'Partial'): ?>
                                            <span class="badge bg-warning bg-opacity-10 text-warning px-2 py-1 fw-bold">Partial</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger bg-opacity-10 text-danger px-2 py-1 fw-bold">Unpaid</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <button type="button" class="btn btn-sm btn-outline-primary shadow-sm" onclick="printInvoiceModal(<?php echo $sale['id']; ?>)" title="Print Bill"><i class="fa-solid fa-print"></i></button>
                                        <a href="?edit_id=<?php echo $sale['id']; ?>" class="btn btn-sm btn-outline-warning shadow-sm text-dark" title="Edit Sale"><i class="fa-solid fa-pen-to-square"></i></a>
                                        <a href="?delete_id=<?php echo $sale['id']; ?>" class="btn btn-sm btn-outline-danger shadow-sm" onclick="return confirm('Are you sure you want to delete this invoice? Stock will be restored.');" title="Delete Sale"><i class="fa-solid fa-trash"></i></a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="10" class="text-center text-muted py-4">No transactions recorded for today yet.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </main>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const defaultGstPercent = parseFloat(document.getElementById('defaultGstPercentage').value) || 0;

        function toggleFullScreen() {
            if (!document.fullscreenElement) {
                document.documentElement.requestFullscreen().catch(err => {});
            } else {
                if (document.exitFullscreen) document.exitFullscreen();
            }
        }

        document.addEventListener('DOMContentLoaded', function(){
            document.querySelectorAll('#itemRows tr').forEach(row => {
                const selectElem = row.querySelector('.product-select');
                if (selectElem && selectElem.selectedIndex > 0) {
                    const selectedOption = selectElem.options[selectElem.selectedIndex];
                    const stock = selectedOption.getAttribute('data-stock') || 0;
                    row.querySelector('.stock-display').value = stock;
                }
                calculateRowTotal(row.querySelector('.qty-input'));
            });

            const params = new URLSearchParams(window.location.search);
            const autoPrintId = parseInt(params.get('auto_print') || '0', 10);
            const emailStatus = params.get('email_status') || '';
            const emailStatusText = document.getElementById('emailStatusText');
            if (emailStatusText) {
                if (emailStatus === 'sent') emailStatusText.textContent = 'Invoice details were emailed successfully. Opening print window…';
                else if (emailStatus === 'failed') emailStatusText.textContent = 'Invoice saved. Invoice details email could not be sent. Check SMTP configuration.';
            }
            if (!autoPrintId) return;

            const printUrl = 'print_invoice.php?id=' + encodeURIComponent(autoPrintId);
            let printWindow = null;

            try {
                printWindow = window.open(printUrl, 'POSInvoicePrint_' + autoPrintId, 'width=1000,height=850,scrollbars=yes,resizable=yes');
            } catch(e) {}

            if (printWindow) {
                const triggerPrint = function(){
                    try { printWindow.focus(); setTimeout(function(){ printWindow.print(); }, 450); } catch(e) {}
                };
                try { printWindow.addEventListener('load', triggerPrint, {once:true}); } catch(e) {}
                setTimeout(triggerPrint, 1200);
            }

            if (window.history && window.history.replaceState) {
                window.history.replaceState({}, document.title, window.location.pathname + window.location.hash);
            }
        });

        document.addEventListener('DOMContentLoaded', function(){
            const search = document.getElementById('ledgerSearch');
            if (!search) return;
            search.addEventListener('input', function(){
                const term = this.value.trim().toLowerCase();
                document.querySelectorAll('.ledger-row').forEach(function(row){
                    row.style.display = row.innerText.toLowerCase().includes(term) ? '' : 'none';
                });
            });
        });

        function updateProductDetails(selectElem) {
            const row = selectElem.closest('tr');
            const selectedOption = selectElem.options[selectElem.selectedIndex];
            const price = selectedOption.getAttribute('data-price') || 0;
            const stock = selectedOption.getAttribute('data-stock') || 0;

            row.querySelector('.price-input').value = parseFloat(price).toFixed(2);
            row.querySelector('.stock-display').value = stock;
            
            const gstInput = row.querySelector('.gst-input');
            if (!gstInput.value || gstInput.value == '') {
                gstInput.value = defaultGstPercent;
            }

            calculateRowTotal(row.querySelector('.qty-input'));
        }

        function calculateRowTotal(elem) {
            const row = elem.closest('tr');
            const qty = parseFloat(row.querySelector('.qty-input').value) || 0;
            const inclusivePrice = parseFloat(row.querySelector('.price-input').value) || 0;
            const rowGstPercent = parseFloat(row.querySelector('.gst-input').value) || 0;
            
            const grossTotal = qty * inclusivePrice;
            let subtotal = 0;
            let tax = 0;

            if (rowGstPercent > 0) {
                subtotal = grossTotal / (1 + (rowGstPercent / 100));
                tax = grossTotal - subtotal;
            } else {
                subtotal = grossTotal;
                tax = 0;
            }

            row.querySelector('.row-subtotal').value = subtotal.toFixed(2);
            row.querySelector('.row-tax').value = tax.toFixed(2);
            row.querySelector('.row-total').value = grossTotal.toFixed(2);
            
            calculateGrandTotal();
        }

        function calculateGrandTotal() {
            let totalSub = 0;
            let totalTax = 0;
            let grandTotal = 0;

            document.querySelectorAll('#itemRows tr').forEach(row => {
                totalSub += parseFloat(row.querySelector('.row-subtotal').value) || 0;
                totalTax += parseFloat(row.querySelector('.row-tax').value) || 0;
                grandTotal += parseFloat(row.querySelector('.row-total').value) || 0;
            });

            document.getElementById('displaySubtotal').innerText = '₹' + totalSub.toFixed(2);
            document.getElementById('displayTaxTotal').innerText = '₹' + totalTax.toFixed(2);
            document.getElementById('displayGrandTotal').innerText = '₹' + grandTotal.toFixed(2);
            calculateChange();
        }

        function calculateChange() {
            const grandTotalText = document.getElementById('displayGrandTotal').innerText.replace('₹', '');
            const grandTotal = parseFloat(grandTotalText) || 0;
            const paid = parseFloat(document.getElementById('paidAmount').value) || 0;
            let balance = grandTotal - paid;
            if(balance < 0) balance = 0;
            document.getElementById('displayBalance').innerText = '₹' + balance.toFixed(2);
        }

        function addRow() {
            const tbody = document.getElementById('itemRows');
            const firstRow = tbody.querySelector('tr');
            const newRow = firstRow.cloneNode(true);
            
            newRow.querySelector('.product-select').selectedIndex = 0;
            newRow.querySelector('.stock-display').value = '0';
            newRow.querySelector('.qty-input').value = '1';
            newRow.querySelector('.price-input').value = '0.00';
            newRow.querySelector('.gst-input').value = defaultGstPercent;
            newRow.querySelector('.row-subtotal').value = '0.00';
            newRow.querySelector('.row-tax').value = '0.00';
            newRow.querySelector('.row-total').value = '0.00';
            
            tbody.appendChild(newRow);
        }

        function removeRow(btn) {
            const tbody = document.getElementById('itemRows');
            if(tbody.querySelectorAll('tr').length > 1) {
                btn.closest('tr').remove();
                calculateGrandTotal();
            } else {
                alert('At least one product item row is required.');
            }
        }

        function printInvoiceModal(saleId) {
            window.open('print_invoice.php?id=' + saleId, '_blank');
        }
    </script>
</body>
</html>
<?php if (ob_get_level() > 0) { ob_end_flush(); } ?>