<?php
session_start();
include_once('../includes/config.php');
include_once('../includes/quick-menu.php');

if (!isset($_SESSION['uid'])) {
    header('location:../logout.php');
    exit();
}

$currentUserId = $_SESSION['uid'];
$userType = $_SESSION['usertype'];

// Handle font settings form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'update_font_settings') {
    $storeCode = 'ST0002';
    
    $companyNameFont = mysqli_real_escape_string($con, $_POST['companyNameFont'] ?? 'Arial');
    $companyNameSize = intval($_POST['companyNameSize'] ?? 20);
    $companyNameColor = mysqli_real_escape_string($con, $_POST['companyNameColor'] ?? '#000000');
    $companyNameWeight = mysqli_real_escape_string($con, $_POST['companyNameWeight'] ?? 'normal');
    $addressFont = mysqli_real_escape_string($con, $_POST['addressFont'] ?? 'Arial');
    $addressSize = intval($_POST['addressSize'] ?? 12);
    $addressColor = mysqli_real_escape_string($con, $_POST['addressColor'] ?? '#000000');
    $addressWeight = mysqli_real_escape_string($con, $_POST['addressWeight'] ?? 'normal');
    $contactFont = mysqli_real_escape_string($con, $_POST['contactFont'] ?? 'Arial');
    $contactSize = intval($_POST['contactSize'] ?? 11);
    $contactColor = mysqli_real_escape_string($con, $_POST['contactColor'] ?? '#000000');
    $contactWeight = mysqli_real_escape_string($con, $_POST['contactWeight'] ?? 'normal');
    $invoiceTitleFont = mysqli_real_escape_string($con, $_POST['invoiceTitleFont'] ?? 'Arial');
    $invoiceTitleSize = intval($_POST['invoiceTitleSize'] ?? 18);
    $invoiceTitleColor = mysqli_real_escape_string($con, $_POST['invoiceTitleColor'] ?? '#000000');
    $invoiceTitleWeight = mysqli_real_escape_string($con, $_POST['invoiceTitleWeight'] ?? 'normal');
    $sectionTitleFont = mysqli_real_escape_string($con, $_POST['sectionTitleFont'] ?? 'Arial');
    $sectionTitleSize = intval($_POST['sectionTitleSize'] ?? 14);
    $sectionTitleColor = mysqli_real_escape_string($con, $_POST['sectionTitleColor'] ?? '#000000');
    $sectionTitleWeight = mysqli_real_escape_string($con, $_POST['sectionTitleWeight'] ?? 'normal');
    $tableHeaderFont = mysqli_real_escape_string($con, $_POST['tableHeaderFont'] ?? 'Arial');
    $tableHeaderSize = intval($_POST['tableHeaderSize'] ?? 11);
    $tableHeaderColor = mysqli_real_escape_string($con, $_POST['tableHeaderColor'] ?? '#000000');
    $tableHeaderWeight = mysqli_real_escape_string($con, $_POST['tableHeaderWeight'] ?? 'bold');
    $tableHeaderBgColor = mysqli_real_escape_string($con, $_POST['tableHeaderBgColor'] ?? '#f0f0f0');
    $tableBodyFont = mysqli_real_escape_string($con, $_POST['tableBodyFont'] ?? 'Arial');
    $tableBodySize = intval($_POST['tableBodySize'] ?? 10);
    $tableBodyColor = mysqli_real_escape_string($con, $_POST['tableBodyColor'] ?? '#000000');
    $tableBodyWeight = mysqli_real_escape_string($con, $_POST['tableBodyWeight'] ?? 'normal');
    $declarationFont = mysqli_real_escape_string($con, $_POST['declarationFont'] ?? 'Arial');
    $declarationSize = intval($_POST['declarationSize'] ?? 9);
    $declarationColor = mysqli_real_escape_string($con, $_POST['declarationColor'] ?? '#000000');
    $declarationWeight = mysqli_real_escape_string($con, $_POST['declarationWeight'] ?? 'normal');
    $footerFont = mysqli_real_escape_string($con, $_POST['footerFont'] ?? '');
    $footerSize = intval($_POST['footerSize'] ?? 10);
    $footerColor = mysqli_real_escape_string($con, $_POST['footerColor'] ?? '#000000');
    $footerWeight = mysqli_real_escape_string($con, $_POST['footerWeight'] ?? 'normal');
    
    // Check if settings exist
    $checkQuery = "SELECT ID FROM tblfont_settings WHERE StoreCode = '$storeCode' LIMIT 1";
    $checkResult = mysqli_query($con, $checkQuery);
    
    if ($checkResult && mysqli_num_rows($checkResult) > 0) {
        // Update existing
        $updateQuery = "UPDATE tblfont_settings SET 
                       CompanyNameFont = '$companyNameFont',
                       CompanyNameSize = $companyNameSize,
                       CompanyNameColor = '$companyNameColor',
                       CompanyNameWeight = '$companyNameWeight',
                       AddressFont = '$addressFont',
                       AddressSize = $addressSize,
                       AddressColor = '$addressColor',
                       AddressWeight = '$addressWeight',
                       ContactFont = '$contactFont',
                       ContactSize = $contactSize,
                       ContactColor = '$contactColor',
                       ContactWeight = '$contactWeight',
                       InvoiceTitleFont = '$invoiceTitleFont',
                       InvoiceTitleSize = $invoiceTitleSize,
                       InvoiceTitleColor = '$invoiceTitleColor',
                       InvoiceTitleWeight = '$invoiceTitleWeight',
                       SectionTitleFont = '$sectionTitleFont',
                       SectionTitleSize = $sectionTitleSize,
                       SectionTitleColor = '$sectionTitleColor',
                       SectionTitleWeight = '$sectionTitleWeight',
                       TableHeaderFont = '$tableHeaderFont',
                       TableHeaderSize = $tableHeaderSize,
                       TableHeaderColor = '$tableHeaderColor',
                       TableHeaderWeight = '$tableHeaderWeight',
                       TableHeaderBgColor = '$tableHeaderBgColor',
                       TableBodyFont = '$tableBodyFont',
                       TableBodySize = $tableBodySize,
                       TableBodyColor = '$tableBodyColor',
                       TableBodyWeight = '$tableBodyWeight',
                       DeclarationFont = '$declarationFont',
                       DeclarationSize = $declarationSize,
                       DeclarationColor = '$declarationColor',
                       DeclarationWeight = '$declarationWeight',
                       FooterFont = '$footerFont',
                       FooterSize = $footerSize,
                       FooterColor = '$footerColor',
                       FooterWeight = '$footerWeight',
                       LastUpdated = NOW()
                       WHERE StoreCode = '$storeCode'";
        
        if (mysqli_query($con, $updateQuery)) {
            $success = "Font settings updated successfully!";
        } else {
            $error = "Error updating font settings: " . mysqli_error($con);
        }
    } else {
        // Insert new
        $insertQuery = "INSERT INTO tblfont_settings 
                       (StoreCode, CompanyNameFont, CompanyNameSize, CompanyNameColor, CompanyNameWeight, AddressFont, AddressSize, AddressColor, AddressWeight,
                        ContactFont, ContactSize, ContactColor, ContactWeight, InvoiceTitleFont, InvoiceTitleSize, InvoiceTitleColor, InvoiceTitleWeight,
                        SectionTitleFont, SectionTitleSize, SectionTitleColor, SectionTitleWeight, TableHeaderFont, TableHeaderSize, TableHeaderColor, TableHeaderWeight, TableHeaderBgColor,
                        TableBodyFont, TableBodySize, TableBodyColor, TableBodyWeight, DeclarationFont, DeclarationSize, DeclarationColor, DeclarationWeight,
                        FooterFont, FooterSize, FooterColor, FooterWeight, DateAdded)
                       VALUES 
                       ('$storeCode', '$companyNameFont', $companyNameSize, '$companyNameColor', '$companyNameWeight', '$addressFont', $addressSize, '$addressColor', '$addressWeight',
                        '$contactFont', $contactSize, '$contactColor', '$contactWeight', '$invoiceTitleFont', $invoiceTitleSize, '$invoiceTitleColor', '$invoiceTitleWeight',
                        '$sectionTitleFont', $sectionTitleSize, '$sectionTitleColor', '$sectionTitleWeight', '$tableHeaderFont', $tableHeaderSize, '$tableHeaderColor', '$tableHeaderWeight', '$tableHeaderBgColor',
                        '$tableBodyFont', $tableBodySize, '$tableBodyColor', '$tableBodyWeight', '$declarationFont', $declarationSize, '$declarationColor', '$declarationWeight',
                        '$footerFont', $footerSize, '$footerColor', '$footerWeight', NOW())";
        
        if (mysqli_query($con, $insertQuery)) {
            $success = "Font settings created successfully!";
        } else {
            $error = "Error creating font settings: " . mysqli_error($con);
        }
    }
}

// Handle invoice settings form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'update_invoice_settings') {
    $storeCode = 'ST0002';
    
    $showSerialNumber = isset($_POST['showSerialNumber']) ? 1 : 0;
    $showDescription = isset($_POST['showDescription']) ? 1 : 0;
    $showHSN = isset($_POST['showHSN']) ? 1 : 0;
    $showQuantity = isset($_POST['showQuantity']) ? 1 : 0;
    $showMRP = isset($_POST['showMRP']) ? 1 : 0;
    $showPrice = isset($_POST['showPrice']) ? 1 : 0;
    $showDiscount = isset($_POST['showDiscount']) ? 1 : 0;
    $showBasicRate = isset($_POST['showBasicRate']) ? 1 : 0;
    $showTaxable = isset($_POST['showTaxable']) ? 1 : 0;
    $showGSTPercent = isset($_POST['showGSTPercent']) ? 1 : 0;
    $showGSTAmount = isset($_POST['showGSTAmount']) ? 1 : 0;
    $showTotal = isset($_POST['showTotal']) ? 1 : 0;
    $showShipTo = isset($_POST['showShipTo']) ? 1 : 0;
    $showOtherDetails = isset($_POST['showOtherDetails']) ? 1 : 0;
    $showDeclaration = isset($_POST['showDeclaration']) ? 1 : 0;
    
    $headerSr = mysqli_real_escape_string($con, $_POST['headerSr']);
    $headerDescription = mysqli_real_escape_string($con, $_POST['headerDescription']);
    $headerHSN = mysqli_real_escape_string($con, $_POST['headerHSN']);
    $headerQuantity = mysqli_real_escape_string($con, $_POST['headerQuantity']);
    $headerMRP = mysqli_real_escape_string($con, $_POST['headerMRP']);
    $headerPrice = mysqli_real_escape_string($con, $_POST['headerPrice']);
    $headerDiscount = mysqli_real_escape_string($con, $_POST['headerDiscount']);
    $headerBasicRate = mysqli_real_escape_string($con, $_POST['headerBasicRate']);
    $headerTaxable = mysqli_real_escape_string($con, $_POST['headerTaxable']);
    $headerGSTPercent = mysqli_real_escape_string($con, $_POST['headerGSTPercent']);
    $headerGSTAmount = mysqli_real_escape_string($con, $_POST['headerGSTAmount']);
    $headerTotal = mysqli_real_escape_string($con, $_POST['headerTotal']);
    $declarationText = mysqli_real_escape_string($con, $_POST['declarationText']);
    $footerText = isset($_POST['footerText']) ? mysqli_real_escape_string($con, $_POST['footerText']) : '';
    $gstInvoiceTemplate = isset($_POST['gstInvoiceTemplate']) ? mysqli_real_escape_string($con, $_POST['gstInvoiceTemplate']) : 'sale-invoice-template1.php';
    $nonGstInvoiceTemplate = isset($_POST['nonGstInvoiceTemplate']) ? mysqli_real_escape_string($con, $_POST['nonGstInvoiceTemplate']) : 'nongst-sale-invoice-template1.php';
    
    // Get order values with defaults
    $orderSerialNumber = isset($_POST['orderSerialNumber']) ? intval($_POST['orderSerialNumber']) : 1;
    $orderDescription = isset($_POST['orderDescription']) ? intval($_POST['orderDescription']) : 2;
    $orderHSN = isset($_POST['orderHSN']) ? intval($_POST['orderHSN']) : 3;
    $orderQuantity = isset($_POST['orderQuantity']) ? intval($_POST['orderQuantity']) : 4;
    $orderMRP = isset($_POST['orderMRP']) ? intval($_POST['orderMRP']) : 5;
    $orderPrice = isset($_POST['orderPrice']) ? intval($_POST['orderPrice']) : 6;
    $orderDiscount = isset($_POST['orderDiscount']) ? intval($_POST['orderDiscount']) : 7;
    $orderBasicRate = isset($_POST['orderBasicRate']) ? intval($_POST['orderBasicRate']) : 8;
    $orderTaxable = isset($_POST['orderTaxable']) ? intval($_POST['orderTaxable']) : 9;
    $orderGSTPercent = isset($_POST['orderGSTPercent']) ? intval($_POST['orderGSTPercent']) : 10;
    $orderGSTAmount = isset($_POST['orderGSTAmount']) ? intval($_POST['orderGSTAmount']) : 11;
    $orderTotal = isset($_POST['orderTotal']) ? intval($_POST['orderTotal']) : 12;
    
    // Check if settings exist
    $checkQuery = "SELECT ID FROM tblinvoice_settings WHERE StoreCode = '$storeCode' LIMIT 1";
    $checkResult = mysqli_query($con, $checkQuery);
    
    if ($checkResult && mysqli_num_rows($checkResult) > 0) {
        // Update existing
        $updateQuery = "UPDATE tblinvoice_settings SET 
                       ShowSerialNumber = $showSerialNumber,
                       ShowDescription = $showDescription,
                       ShowHSN = $showHSN,
                       ShowQuantity = $showQuantity,
                       ShowMRP = $showMRP,
                       ShowPrice = $showPrice,
                       ShowDiscount = $showDiscount,
                       ShowBasicRate = $showBasicRate,
                       ShowTaxable = $showTaxable,
                       ShowGSTPercent = $showGSTPercent,
                       ShowGSTAmount = $showGSTAmount,
                       ShowTotal = $showTotal,
                       ShowShipTo = $showShipTo,
                       ShowOtherDetails = $showOtherDetails,
                       ShowDeclaration = $showDeclaration,
                       HeaderSr = '$headerSr',
                       HeaderDescription = '$headerDescription',
                       HeaderHSN = '$headerHSN',
                       HeaderQuantity = '$headerQuantity',
                       HeaderMRP = '$headerMRP',
                       HeaderPrice = '$headerPrice',
                       HeaderDiscount = '$headerDiscount',
                       HeaderBasicRate = '$headerBasicRate',
                       HeaderTaxable = '$headerTaxable',
                       HeaderGSTPercent = '$headerGSTPercent',
                       HeaderGSTAmount = '$headerGSTAmount',
                       HeaderTotal = '$headerTotal',
                       OrderSerialNumber = $orderSerialNumber,
                       OrderDescription = $orderDescription,
                       OrderHSN = $orderHSN,
                       OrderQuantity = $orderQuantity,
                       OrderMRP = $orderMRP,
                       OrderPrice = $orderPrice,
                       OrderDiscount = $orderDiscount,
                       OrderBasicRate = $orderBasicRate,
                       OrderTaxable = $orderTaxable,
                       OrderGSTPercent = $orderGSTPercent,
                       OrderGSTAmount = $orderGSTAmount,
                       OrderTotal = $orderTotal,
                       DeclarationText = '$declarationText',
                       FooterText = '$footerText',
                       GstInvoiceTemplate = '$gstInvoiceTemplate',
                       NonGstInvoiceTemplate = '$nonGstInvoiceTemplate',
                       ShowFooter = $showDeclaration,
                       LastUpdated = NOW()
                       WHERE StoreCode = '$storeCode'";
        
        if (mysqli_query($con, $updateQuery)) {
            $success = "Invoice settings updated successfully!";
        } else {
            $error = "Error updating invoice settings: " . mysqli_error($con);
        }
    } else {
        // Insert new
        $insertQuery = "INSERT INTO tblinvoice_settings 
                       (StoreCode, ShowSerialNumber, OrderSerialNumber, ShowDescription, OrderDescription, ShowHSN, OrderHSN, ShowQuantity, OrderQuantity, 
                        ShowMRP, OrderMRP, ShowPrice, OrderPrice, ShowDiscount, OrderDiscount,
                        ShowBasicRate, OrderBasicRate, ShowTaxable, OrderTaxable, ShowGSTPercent, OrderGSTPercent, 
                        ShowGSTAmount, OrderGSTAmount, ShowTotal, OrderTotal,
                        ShowShipTo, ShowOtherDetails, ShowDeclaration,
                        HeaderSr, HeaderDescription, HeaderHSN, HeaderQuantity, HeaderMRP, HeaderPrice, HeaderDiscount,
                        HeaderBasicRate, HeaderTaxable, HeaderGSTPercent, HeaderGSTAmount, HeaderTotal,
                        DeclarationText, FooterText, GstInvoiceTemplate, NonGstInvoiceTemplate, ShowFooter, DateAdded)
                       VALUES 
                       ('$storeCode', $showSerialNumber, $orderSerialNumber, $showDescription, $orderDescription, $showHSN, $orderHSN, $showQuantity, $orderQuantity,
                        $showMRP, $orderMRP, $showPrice, $orderPrice, $showDiscount, $orderDiscount,
                        $showBasicRate, $orderBasicRate, $showTaxable, $orderTaxable, $showGSTPercent, $orderGSTPercent,
                        $showGSTAmount, $orderGSTAmount, $showTotal, $orderTotal,
                        $showShipTo, $showOtherDetails, $showDeclaration,
                        '$headerSr', '$headerDescription', '$headerHSN', '$headerQuantity', '$headerMRP', '$headerPrice', '$headerDiscount',
                        '$headerBasicRate', '$headerTaxable', '$headerGSTPercent', '$headerGSTAmount', '$headerTotal',
                        '$declarationText', '$footerText', '$gstInvoiceTemplate', '$nonGstInvoiceTemplate', $showDeclaration, NOW())";
        
        if (mysqli_query($con, $insertQuery)) {
            $success = "Invoice settings created successfully!";
        } else {
            $error = "Error creating invoice settings: " . mysqli_error($con);
        }
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'update_store') {
    $storeCode = mysqli_real_escape_string($con, $_POST['storeCode']);
    $storeName = mysqli_real_escape_string($con, $_POST['storeName']);
    $mobile = mysqli_real_escape_string($con, $_POST['mobile']);
    $email = mysqli_real_escape_string($con, $_POST['email']);
    $phone = mysqli_real_escape_string($con, $_POST['phone']);
    $gstNumber = mysqli_real_escape_string($con, $_POST['gstNumber']);
    $taxNumber = mysqli_real_escape_string($con, $_POST['taxNumber']);
    $panNumber = mysqli_real_escape_string($con, $_POST['panNumber']);
    $storeWebsite = mysqli_real_escape_string($con, $_POST['storeWebsite']);
    $showSignature = isset($_POST['showSignatureOnInvoice']) ? 1 : 0;
    $bankDetails = mysqli_real_escape_string($con, $_POST['bankDetails']);
    $country = mysqli_real_escape_string($con, $_POST['country']);
    $state = mysqli_real_escape_string($con, $_POST['state']);
    $city = mysqli_real_escape_string($con, $_POST['city']);
    $postcode = mysqli_real_escape_string($con, $_POST['postcode']);
    $address = mysqli_real_escape_string($con, $_POST['address']);
    
    // Handle file uploads
    $uploadDir = '../uploads/store/';
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    $signatureImage = '';
    $storeLogo1 = '';
    $storeLogo2 = '';
    
    // Get existing values
    $existingQuery = "SELECT SignatureImage, StoreLogo1, StoreLogo2 FROM tblstore_settings WHERE StoreCode = '$storeCode' LIMIT 1";
    $existingResult = mysqli_query($con, $existingQuery);
    if ($existingResult && mysqli_num_rows($existingResult) > 0) {
        $existing = mysqli_fetch_assoc($existingResult);
        $signatureImage = $existing['SignatureImage'];
        $storeLogo1 = $existing['StoreLogo1'];
        $storeLogo2 = $existing['StoreLogo2'];
    }
    
    // Upload Signature
    if (isset($_FILES['signatureImage']) && $_FILES['signatureImage']['error'] == 0) {
        $fileName = 'signature_' . time() . '_' . basename($_FILES['signatureImage']['name']);
        $targetFile = $uploadDir . $fileName;
        if (move_uploaded_file($_FILES['signatureImage']['tmp_name'], $targetFile)) {
            $signatureImage = 'uploads/store/' . $fileName;
        }
    }
    
    // Upload Store Logo 1
    if (isset($_FILES['storeLogo1']) && $_FILES['storeLogo1']['error'] == 0) {
        $fileName = 'logo1_' . time() . '_' . basename($_FILES['storeLogo1']['name']);
        $targetFile = $uploadDir . $fileName;
        if (move_uploaded_file($_FILES['storeLogo1']['tmp_name'], $targetFile)) {
            $storeLogo1 = 'uploads/store/' . $fileName;
        }
    }
    
    // Upload Store Logo 2
    if (isset($_FILES['storeLogo2']) && $_FILES['storeLogo2']['error'] == 0) {
        $fileName = 'logo2_' . time() . '_' . basename($_FILES['storeLogo2']['name']);
        $targetFile = $uploadDir . $fileName;
        if (move_uploaded_file($_FILES['storeLogo2']['tmp_name'], $targetFile)) {
            $storeLogo2 = 'uploads/store/' . $fileName;
        }
    }
    
    // Check if store settings exist
    $checkQuery = "SELECT ID FROM tblstore_settings WHERE StoreCode = '$storeCode' LIMIT 1";
    $checkResult = mysqli_query($con, $checkQuery);
    
    if ($checkResult && mysqli_num_rows($checkResult) > 0) {
        // Update existing
        $updateQuery = "UPDATE tblstore_settings SET 
                       StoreName = '$storeName',
                       Mobile = '$mobile',
                       Email = '$email',
                       Phone = '$phone',
                       GSTNumber = '$gstNumber',
                       TaxNumber = '$taxNumber',
                       PANNumber = '$panNumber',
                       StoreWebsite = '$storeWebsite',
                       ShowSignatureOnInvoice = $showSignature,
                       SignatureImage = '$signatureImage',
                       BankDetails = '$bankDetails',
                       Country = '$country',
                       State = '$state',
                       City = '$city',
                       Postcode = '$postcode',
                       Address = '$address',
                       StoreLogo1 = '$storeLogo1',
                       StoreLogo2 = '$storeLogo2',
                       LastUpdated = NOW()
                       WHERE StoreCode = '$storeCode'";
        
        if (mysqli_query($con, $updateQuery)) {
            $success = "Store settings updated successfully!";
        } else {
            $error = "Error updating store settings: " . mysqli_error($con);
        }
    } else {
        // Insert new
        $insertQuery = "INSERT INTO tblstore_settings 
                       (StoreCode, StoreName, Mobile, Email, Phone, GSTNumber, TaxNumber, PANNumber, 
                        StoreWebsite, ShowSignatureOnInvoice, SignatureImage, BankDetails, Country, State, 
                        City, Postcode, Address, StoreLogo1, StoreLogo2, DateAdded)
                       VALUES 
                       ('$storeCode', '$storeName', '$mobile', '$email', '$phone', '$gstNumber', '$taxNumber', 
                        '$panNumber', '$storeWebsite', $showSignature, '$signatureImage', '$bankDetails', 
                        '$country', '$state', '$city', '$postcode', '$address', '$storeLogo1', '$storeLogo2', NOW())";
        
        if (mysqli_query($con, $insertQuery)) {
            $success = "Store settings created successfully!";
        } else {
            $error = "Error creating store settings: " . mysqli_error($con);
        }
    }
}

// Get store settings
$settingsQuery = "SELECT * FROM tblstore_settings WHERE StoreCode = 'ST0002' LIMIT 1";
$settingsResult = mysqli_query($con, $settingsQuery);
$storeSettings = null;

if ($settingsResult && mysqli_num_rows($settingsResult) > 0) {
    $storeSettings = mysqli_fetch_assoc($settingsResult);
}

// Get invoice settings
$invoiceSettingsQuery = "SELECT * FROM tblinvoice_settings WHERE StoreCode = 'ST0002' LIMIT 1";
$invoiceSettingsResult = mysqli_query($con, $invoiceSettingsQuery);
$invoiceSettings = null;

if ($invoiceSettingsResult && mysqli_num_rows($invoiceSettingsResult) > 0) {
    $invoiceSettings = mysqli_fetch_assoc($invoiceSettingsResult);
}

$selectedGstTemplate = 'sale-invoice-template1.php';
if ($invoiceSettings) {
    if (!empty($invoiceSettings['GstInvoiceTemplate'])) {
        $selectedGstTemplate = $invoiceSettings['GstInvoiceTemplate'];
    } elseif (!empty($invoiceSettings['InvoiceTemplate'])) {
        $selectedGstTemplate = $invoiceSettings['InvoiceTemplate'];
    }
}

$selectedNonGstTemplate = ($invoiceSettings && !empty($invoiceSettings['NonGstInvoiceTemplate']))
    ? $invoiceSettings['NonGstInvoiceTemplate']
    : 'nongst-sale-invoice-template1.php';

// Get font settings
$fontSettingsQuery = "SELECT * FROM tblfont_settings WHERE StoreCode = 'ST0002' LIMIT 1";
$fontSettingsResult = mysqli_query($con, $fontSettingsQuery);
$fontSettings = null;

if ($fontSettingsResult && mysqli_num_rows($fontSettingsResult) > 0) {
    $fontSettings = mysqli_fetch_assoc($fontSettingsResult);
}

// Available fonts for dropdown
$availableFonts = [
    'Arial',
    'Times New Roman',
    'Courier New',
    'Georgia',
    'Verdana',
    'Tahoma',
    'Trebuchet MS',
    'Calibri',
    'Cambria',
    'Segoe UI',
    'Poppins',
    'Roboto',
    'Open Sans',
    'Lato',
    'Montserrat'
];

$gstInvoiceTemplates = [
    'sale-invoice-template1.php' => 'Template 1 - GST Standard (A4)',
    'sale-invoice-template-a5.php' => 'Template 2 - GST A5 Portrait',
    'sale-invoice-template-a5-horizontal.php' => 'Template 3 - GST A5 Landscape',
    'sale-invoice-template-thermal1.php' => 'Template 4 - GST Thermal (80mm)'
];

$nonGstInvoiceTemplates = [
    'nongst-sale-invoice-template1.php' => 'Format 1 - Sales Standard (A4)',
    'nongst-sale-invoice-template-a5.php' => 'Format 2 - Sales A5 Portrait',
    'nongst-sale-invoice-template-thermal1.php' => 'Format 3 - Sales Thermal (80mm)'
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>UZRS Inventory | Store Settings</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/modern-messagebox.css" rel="stylesheet">
    <link href="css/store-settings.css?v=<?php echo time(); ?>" rel="stylesheet">
    <?php renderQuickMenuCSS(); ?>
    <style>
        /* Maximize viewport usage - Compact Layout */
        #content-wrapper {
            padding: 0 !important;
        }
        #content {
            padding: 0 !important;
        }
        body {
            overflow-x: hidden;
        }
        /* Remove default Bootstrap container padding */
        .container-fluid {
            padding-left: 8px !important;
            padding-right: 8px !important;
            padding-top: 5px !important;
            padding-bottom: 5px !important;
        }
        /* Compact topbar */
        .topbar {
            height: 50px !important;
            padding: 0 10px !important;
        }
        /* Make content full width */
        #wrapper #content-wrapper {
            width: 100%;
            overflow-x: hidden;
        }
        /* Reduce footer padding */
        .sticky-footer {
            padding: 8px 0 !important;
            font-size: 0.75rem;
        }
        .sticky-footer .copyright {
            margin: 0 !important;
        }
        
        /* FORCE 4 COLUMNS ON DESKTOP - DIRECT OVERRIDE */
        .card-body .row > .col-md-6,
        .tab-pane .row > .col-md-6,
        form .row > .col-md-6 {
            -ms-flex: 0 0 25% !important;
            flex: 0 0 25% !important;
            max-width: 25% !important;
            width: 25% !important;
        }
        
        .card-body .row > .col-md-4,
        .tab-pane .row > .col-md-4,
        form .row > .col-md-4 {
            -ms-flex: 0 0 25% !important;
            flex: 0 0 25% !important;
            max-width: 25% !important;
            width: 25% !important;
        }
        
        .card-body .row > .col-md-8,
        .tab-pane .row > .col-md-8,
        form .row > .col-md-8 {
            -ms-flex: 0 0 50% !important;
            flex: 0 0 50% !important;
            max-width: 50% !important;
            width: 50% !important;
        }
        
        .card-body .row > .col-md-12,
        .tab-pane .row > .col-md-12,
        form .row > .col-md-12 {
            -ms-flex: 0 0 100% !important;
            flex: 0 0 100% !important;
            max-width: 100% !important;
            width: 100% !important;
        }
        
        /* 2 COLUMNS ON MOBILE ONLY */
        @media (max-width: 767px) {
            .card-body .row > .col-md-6,
            .card-body .row > .col-md-4,
            .tab-pane .row > .col-md-6,
            .tab-pane .row > .col-md-4,
            form .row > .col-md-6,
            form .row > .col-md-4 {
                -ms-flex: 0 0 50% !important;
                flex: 0 0 50% !important;
                max-width: 50% !important;
                width: 50% !important;
            }
            
            .card-body .row > .col-md-8,
            .tab-pane .row > .col-md-8,
            form .row > .col-md-8 {
                -ms-flex: 0 0 100% !important;
                flex: 0 0 100% !important;
                max-width: 100% !important;
                width: 100% !important;
            }
        }
    </style>
</head>
<body id="page-top">
    <div id="wrapper">
        <?php include_once('../includes/sidebar.php');?>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include_once('../includes/topbar.php');?>
                
                <div class="container-fluid">
                    
                    <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
                        <button type="button" class="close" data-dismiss="alert">
                            <span>&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
                        <button type="button" class="close" data-dismiss="alert">
                            <span>&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>

                    <?php renderQuickMenu("Store Settings", "Configure your store details"); ?>
                    
                    <!-- Store Settings Form with Tabs -->
                    <div class="card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary">
                                <i class="fas fa-store mr-2"></i>Store Configuration
                            </h6>
                        </div>
                        <div class="card-body">
                            <!-- Tab Navigation -->
                            <ul class="nav nav-tabs mb-4" id="storeSettingsTabs" role="tablist">
                                <li class="nav-item">
                                    <a class="nav-link active" id="store-details-tab" data-toggle="tab" href="#store-details" role="tab">
                                        <i class="fas fa-store mr-1"></i>Store Details
                                    </a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link" id="invoice-settings-tab" data-toggle="tab" href="#invoice-settings" role="tab">
                                        <i class="fas fa-file-invoice mr-1"></i>Invoice Settings
                                    </a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link" id="font-settings-tab" data-toggle="tab" href="#font-settings" role="tab">
                                        <i class="fas fa-font mr-1"></i>Invoice Font Settings
                                    </a>
                                </li>
                            </ul>
                            
                            <!-- Tab Content -->
                            <div class="tab-content" id="storeSettingsTabContent">
                                <!-- Store Details Tab -->
                                <div class="tab-pane fade show active" id="store-details" role="tabpanel">
                            <form method="POST" enctype="multipart/form-data" id="storeSettingsForm">
                                <input type="hidden" name="action" value="update_store">
                                
                                <div class="row">
                                    <!-- Store Code -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="storeCode">Store Code <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" id="storeCode" name="storeCode" 
                                                   value="<?php echo $storeSettings ? $storeSettings['StoreCode'] : 'ST0002'; ?>" 
                                                   readonly required>
                                        </div>
                                    </div>
                                    
                                    <!-- Store Name -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="storeName">Store Name <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" id="storeName" name="storeName" 
                                                   value="<?php echo $storeSettings ? $storeSettings['StoreName'] : ''; ?>" 
                                                   required>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <!-- Mobile -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="mobile">Mobile <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" id="mobile" name="mobile" 
                                                   value="<?php echo $storeSettings ? $storeSettings['Mobile'] : ''; ?>" 
                                                   required>
                                        </div>
                                    </div>
                                    
                                    <!-- Email -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="email">Email <span class="text-danger">*</span></label>
                                            <input type="email" class="form-control" id="email" name="email" 
                                                   value="<?php echo $storeSettings ? $storeSettings['Email'] : ''; ?>" 
                                                   required>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <!-- Phone -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="phone">Phone</label>
                                            <input type="text" class="form-control" id="phone" name="phone" 
                                                   value="<?php echo $storeSettings ? $storeSettings['Phone'] : ''; ?>">
                                        </div>
                                    </div>
                                    
                                    <!-- Store Website -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="storeWebsite">Store Website</label>
                                            <input type="text" class="form-control" id="storeWebsite" name="storeWebsite" 
                                                   value="<?php echo $storeSettings ? $storeSettings['StoreWebsite'] : ''; ?>">
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <!-- GST Number -->
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label for="gstNumber">GST Number</label>
                                            <input type="text" class="form-control" id="gstNumber" name="gstNumber" 
                                                   value="<?php echo $storeSettings ? $storeSettings['GSTNumber'] : ''; ?>">
                                        </div>
                                    </div>
                                    
                                    <!-- Tax Number -->
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label for="taxNumber">Tax Number</label>
                                            <input type="text" class="form-control" id="taxNumber" name="taxNumber" 
                                                   value="<?php echo $storeSettings ? $storeSettings['TaxNumber'] : ''; ?>">
                                        </div>
                                    </div>
                                    
                                    <!-- PAN Number -->
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label for="panNumber">PAN Number</label>
                                            <input type="text" class="form-control" id="panNumber" name="panNumber" 
                                                   value="<?php echo $storeSettings ? $storeSettings['PANNumber'] : ''; ?>">
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Bank Details -->
                                <div class="form-group">
                                    <label for="bankDetails">Bank Details</label>
                                    <textarea class="form-control" id="bankDetails" name="bankDetails" rows="3" 
                                              placeholder="Ac. Name: YOUR BANK NAME&#10;Ac. No: 1234567890&#10;IFSC: XXXX0001234"><?php echo $storeSettings ? $storeSettings['BankDetails'] : ''; ?></textarea>
                                </div>
                                
                                <div class="row">
                                    <!-- Country -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="country">Country</label>
                                            <select class="form-control" id="country" name="country">
                                                <option value="India" <?php echo ($storeSettings && $storeSettings['Country'] == 'India') ? 'selected' : ''; ?>>India</option>
                                                <option value="USA" <?php echo ($storeSettings && $storeSettings['Country'] == 'USA') ? 'selected' : ''; ?>>USA</option>
                                                <option value="UK" <?php echo ($storeSettings && $storeSettings['Country'] == 'UK') ? 'selected' : ''; ?>>UK</option>
                                                <option value="Australia" <?php echo ($storeSettings && $storeSettings['Country'] == 'Australia') ? 'selected' : ''; ?>>Australia</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <!-- State -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="state">State</label>
                                            <select class="form-control" id="state" name="state">
                                                <option value="">Select State</option>
                                                <option value="Tamil Nadu" <?php echo ($storeSettings && $storeSettings['State'] == 'Tamil Nadu') ? 'selected' : ''; ?>>Tamil Nadu</option>
                                                <option value="Kerala" <?php echo ($storeSettings && $storeSettings['State'] == 'Kerala') ? 'selected' : ''; ?>>Kerala</option>
                                                <option value="Karnataka" <?php echo ($storeSettings && $storeSettings['State'] == 'Karnataka') ? 'selected' : ''; ?>>Karnataka</option>
                                                <option value="Maharashtra" <?php echo ($storeSettings && $storeSettings['State'] == 'Maharashtra') ? 'selected' : ''; ?>>Maharashtra</option>
                                                <option value="Delhi" <?php echo ($storeSettings && $storeSettings['State'] == 'Delhi') ? 'selected' : ''; ?>>Delhi</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <!-- City -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="city">City</label>
                                            <input type="text" class="form-control" id="city" name="city" 
                                                   value="<?php echo $storeSettings ? $storeSettings['City'] : ''; ?>">
                                        </div>
                                    </div>
                                    
                                    <!-- Postcode -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="postcode">Postcode</label>
                                            <input type="text" class="form-control" id="postcode" name="postcode" 
                                                   value="<?php echo $storeSettings ? $storeSettings['Postcode'] : ''; ?>">
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Address -->
                                <div class="form-group">
                                    <label for="address">Address</label>
                                    <textarea class="form-control" id="address" name="address" rows="2"><?php echo $storeSettings ? $storeSettings['Address'] : ''; ?></textarea>
                                </div>
                                
                                <!-- Show Signature on Invoice -->
                                <div class="form-group">
                                    <div class="custom-control custom-checkbox">
                                        <input type="checkbox" class="custom-control-input" id="showSignatureOnInvoice" 
                                               name="showSignatureOnInvoice" 
                                               <?php echo ($storeSettings && $storeSettings['ShowSignatureOnInvoice']) ? 'checked' : ''; ?>>
                                        <label class="custom-control-label" for="showSignatureOnInvoice">
                                            Show Signature on Invoice
                                        </label>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <!-- Signature Upload -->
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label for="signatureImage">Signature Upload</label>
                                            <input type="file" class="form-control-file" id="signatureImage" name="signatureImage" accept="image/*">
                                            <small class="form-text text-muted">Max: 1024KB, 1000×1000px</small>
                                            <?php if ($storeSettings && $storeSettings['SignatureImage']): ?>
                                            <div class="mt-2">
                                                <img src="../<?php echo $storeSettings['SignatureImage']; ?>" 
                                                     alt="Signature" class="img-thumbnail" style="max-width: 150px;">
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <!-- Store Logo 1 -->
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label for="storeLogo1">Store Logo 1</label>
                                            <input type="file" class="form-control-file" id="storeLogo1" name="storeLogo1" accept="image/*">
                                            <small class="form-text text-muted">Max: 1024KB, 1000×1000px</small>
                                            <?php if ($storeSettings && $storeSettings['StoreLogo1']): ?>
                                            <div class="mt-2">
                                                <img src="../<?php echo $storeSettings['StoreLogo1']; ?>" 
                                                     alt="Logo 1" class="img-thumbnail" style="max-width: 150px;">
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <!-- Store Logo 2 -->
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label for="storeLogo2">Store Logo 2</label>
                                            <input type="file" class="form-control-file" id="storeLogo2" name="storeLogo2" accept="image/*">
                                            <small class="form-text text-muted">Max: 1024KB, 1000×1000px</small>
                                            <?php if ($storeSettings && $storeSettings['StoreLogo2']): ?>
                                            <div class="mt-2">
                                                <img src="../<?php echo $storeSettings['StoreLogo2']; ?>" 
                                                     alt="Logo 2" class="img-thumbnail" style="max-width: 150px;">
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="form-group mt-4">
                                    <button type="submit" class="btn btn-primary btn-lg btn-block">
                                        <i class="fas fa-save mr-2"></i>Save Store Settings
                                    </button>
                                </div>
                            </form>
                                </div>
                                <!-- End Store Details Tab -->
                                
                                <!-- Invoice Settings Tab -->
                                <div class="tab-pane fade" id="invoice-settings" role="tabpanel">
                                    <form method="POST" id="invoiceSettingsForm">
                                        <input type="hidden" name="action" value="update_invoice_settings">
                                        
                                        <h5 class="text-primary mb-3">
                                            <i class="fas fa-table mr-2"></i>Invoice Column Visibility & Order
                                        </h5>
                                        
                                        <div class="row">
                                            <!-- Serial Number -->
                                            <div class="col-md-4 col-sm-6">
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="custom-control custom-checkbox flex-grow-1">
                                                        <input type="checkbox" class="custom-control-input" id="showSerialNumber" 
                                                               name="showSerialNumber" value="1"
                                                               <?php echo ($invoiceSettings && $invoiceSettings['ShowSerialNumber']) ? 'checked' : ''; ?>>
                                                        <label class="custom-control-label" for="showSerialNumber">Sr. No.</label>
                                                    </div>
                                                    <input type="number" class="form-control form-control-sm ml-2" name="orderSerialNumber" 
                                                           value="<?php echo $invoiceSettings ? $invoiceSettings['OrderSerialNumber'] : 1; ?>" 
                                                           min="1" max="12" style="width: 60px;" title="Order">
                                                </div>
                                            </div>
                                            
                                            <!-- Description -->
                                            <div class="col-md-4 col-sm-6">
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="custom-control custom-checkbox flex-grow-1">
                                                        <input type="checkbox" class="custom-control-input" id="showDescription" 
                                                               name="showDescription" value="1"
                                                               <?php echo ($invoiceSettings && $invoiceSettings['ShowDescription']) ? 'checked' : 'checked'; ?>>
                                                        <label class="custom-control-label" for="showDescription">Description</label>
                                                    </div>
                                                    <input type="number" class="form-control form-control-sm ml-2" name="orderDescription" 
                                                           value="<?php echo $invoiceSettings && isset($invoiceSettings['OrderDescription']) ? $invoiceSettings['OrderDescription'] : 2; ?>" 
                                                           min="1" max="12" style="width: 60px;" title="Order">
                                                </div>
                                            </div>
                                            
                                            <!-- HSN -->
                                            <div class="col-md-4 col-sm-6">
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="custom-control custom-checkbox flex-grow-1">
                                                        <input type="checkbox" class="custom-control-input" id="showHSN" 
                                                               name="showHSN" value="1"
                                                               <?php echo ($invoiceSettings && $invoiceSettings['ShowHSN']) ? 'checked' : ''; ?>>
                                                        <label class="custom-control-label" for="showHSN">HSN</label>
                                                    </div>
                                                    <input type="number" class="form-control form-control-sm ml-2" name="orderHSN" 
                                                           value="<?php echo $invoiceSettings ? $invoiceSettings['OrderHSN'] : 3; ?>" 
                                                           min="1" max="12" style="width: 60px;" title="Order">
                                                </div>
                                            </div>
                                            
                                            <!-- Quantity -->
                                            <div class="col-md-4 col-sm-6">
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="custom-control custom-checkbox flex-grow-1">
                                                        <input type="checkbox" class="custom-control-input" id="showQuantity" 
                                                               name="showQuantity" value="1"
                                                               <?php echo ($invoiceSettings && $invoiceSettings['ShowQuantity']) ? 'checked' : ''; ?>>
                                                        <label class="custom-control-label" for="showQuantity">Quantity</label>
                                                    </div>
                                                    <input type="number" class="form-control form-control-sm ml-2" name="orderQuantity" 
                                                           value="<?php echo $invoiceSettings ? $invoiceSettings['OrderQuantity'] : 4; ?>" 
                                                           min="1" max="12" style="width: 60px;" title="Order">
                                                </div>
                                            </div>
                                            
                                            <!-- MRP -->
                                            <div class="col-md-4 col-sm-6">
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="custom-control custom-checkbox flex-grow-1">
                                                        <input type="checkbox" class="custom-control-input" id="showMRP" 
                                                               name="showMRP" value="1"
                                                               <?php echo ($invoiceSettings && $invoiceSettings['ShowMRP']) ? 'checked' : ''; ?>>
                                                        <label class="custom-control-label" for="showMRP">MRP</label>
                                                    </div>
                                                    <input type="number" class="form-control form-control-sm ml-2" name="orderMRP" 
                                                           value="<?php echo $invoiceSettings ? $invoiceSettings['OrderMRP'] : 5; ?>" 
                                                           min="1" max="12" style="width: 60px;" title="Order">
                                                </div>
                                            </div>
                                            
                                            <!-- Price -->
                                            <div class="col-md-4 col-sm-6">
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="custom-control custom-checkbox flex-grow-1">
                                                        <input type="checkbox" class="custom-control-input" id="showPrice" 
                                                               name="showPrice" value="1"
                                                               <?php echo ($invoiceSettings && $invoiceSettings['ShowPrice']) ? 'checked' : ''; ?>>
                                                        <label class="custom-control-label" for="showPrice">Price</label>
                                                    </div>
                                                    <input type="number" class="form-control form-control-sm ml-2" name="orderPrice" 
                                                           value="<?php echo $invoiceSettings ? $invoiceSettings['OrderPrice'] : 6; ?>" 
                                                           min="1" max="12" style="width: 60px;" title="Order">
                                                </div>
                                            </div>
                                            
                                            <!-- Discount -->
                                            <div class="col-md-4 col-sm-6">
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="custom-control custom-checkbox flex-grow-1">
                                                        <input type="checkbox" class="custom-control-input" id="showDiscount" 
                                                               name="showDiscount" value="1"
                                                               <?php echo ($invoiceSettings && $invoiceSettings['ShowDiscount']) ? 'checked' : ''; ?>>
                                                        <label class="custom-control-label" for="showDiscount">Discount</label>
                                                    </div>
                                                    <input type="number" class="form-control form-control-sm ml-2" name="orderDiscount" 
                                                           value="<?php echo $invoiceSettings ? $invoiceSettings['OrderDiscount'] : 7; ?>" 
                                                           min="1" max="12" style="width: 60px;" title="Order">
                                                </div>
                                            </div>
                                            
                                            <!-- Basic Rate -->
                                            <div class="col-md-4 col-sm-6">
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="custom-control custom-checkbox flex-grow-1">
                                                        <input type="checkbox" class="custom-control-input" id="showBasicRate" 
                                                               name="showBasicRate" value="1"
                                                               <?php echo ($invoiceSettings && $invoiceSettings['ShowBasicRate']) ? 'checked' : ''; ?>>
                                                        <label class="custom-control-label" for="showBasicRate">Basic Rate</label>
                                                    </div>
                                                    <input type="number" class="form-control form-control-sm ml-2" name="orderBasicRate" 
                                                           value="<?php echo $invoiceSettings ? $invoiceSettings['OrderBasicRate'] : 8; ?>" 
                                                           min="1" max="12" style="width: 60px;" title="Order">
                                                </div>
                                            </div>
                                            
                                            <!-- Taxable -->
                                            <div class="col-md-4 col-sm-6">
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="custom-control custom-checkbox flex-grow-1">
                                                        <input type="checkbox" class="custom-control-input" id="showTaxable" 
                                                               name="showTaxable" value="1"
                                                               <?php echo ($invoiceSettings && $invoiceSettings['ShowTaxable']) ? 'checked' : ''; ?>>
                                                        <label class="custom-control-label" for="showTaxable">Taxable</label>
                                                    </div>
                                                    <input type="number" class="form-control form-control-sm ml-2" name="orderTaxable" 
                                                           value="<?php echo $invoiceSettings ? $invoiceSettings['OrderTaxable'] : 9; ?>" 
                                                           min="1" max="12" style="width: 60px;" title="Order">
                                                </div>
                                            </div>
                                            
                                            <!-- GST Percent -->
                                            <div class="col-md-4 col-sm-6">
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="custom-control custom-checkbox flex-grow-1">
                                                        <input type="checkbox" class="custom-control-input" id="showGSTPercent" 
                                                               name="showGSTPercent" value="1"
                                                               <?php echo ($invoiceSettings && $invoiceSettings['ShowGSTPercent']) ? 'checked' : ''; ?>>
                                                        <label class="custom-control-label" for="showGSTPercent">GST %</label>
                                                    </div>
                                                    <input type="number" class="form-control form-control-sm ml-2" name="orderGSTPercent" 
                                                           value="<?php echo $invoiceSettings ? $invoiceSettings['OrderGSTPercent'] : 10; ?>" 
                                                           min="1" max="12" style="width: 60px;" title="Order">
                                                </div>
                                            </div>
                                            
                                            <!-- GST Amount -->
                                            <div class="col-md-4 col-sm-6">
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="custom-control custom-checkbox flex-grow-1">
                                                        <input type="checkbox" class="custom-control-input" id="showGSTAmount" 
                                                               name="showGSTAmount" value="1"
                                                               <?php echo ($invoiceSettings && $invoiceSettings['ShowGSTAmount']) ? 'checked' : ''; ?>>
                                                        <label class="custom-control-label" for="showGSTAmount">GST Amount</label>
                                                    </div>
                                                    <input type="number" class="form-control form-control-sm ml-2" name="orderGSTAmount" 
                                                           value="<?php echo $invoiceSettings ? $invoiceSettings['OrderGSTAmount'] : 11; ?>" 
                                                           min="1" max="12" style="width: 60px;" title="Order">
                                                </div>
                                            </div>
                                            
                                            <!-- Total -->
                                            <div class="col-md-4 col-sm-6">
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="custom-control custom-checkbox flex-grow-1">
                                                        <input type="checkbox" class="custom-control-input" id="showTotal" 
                                                               name="showTotal" value="1"
                                                               <?php echo ($invoiceSettings && $invoiceSettings['ShowTotal']) ? 'checked' : ''; ?>>
                                                        <label class="custom-control-label" for="showTotal">Total</label>
                                                    </div>
                                                    <input type="number" class="form-control form-control-sm ml-2" name="orderTotal" 
                                                           value="<?php echo $invoiceSettings ? $invoiceSettings['OrderTotal'] : 12; ?>" 
                                                           min="1" max="12" style="width: 60px;" title="Order">
                                                </div>
                                            </div>
                                        </div>
                                        
                        <div class="alert alert-warning mt-2 mb-3">
                            <i class="fas fa-info-circle mr-2"></i>
                            <strong>Column Order:</strong> Use the number inputs (1-12) to set the display order of columns. Lower numbers appear first.
                        </div>                                        <hr class="my-4">
                                        
                                        <h5 class="text-primary mb-3">
                                            <i class="fas fa-edit mr-2"></i>Column Header Customization
                                        </h5>
                                        
                                        <div class="row">
                                            <!-- Header Sr -->
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="headerSr">Sr. Column Header</label>
                                                    <input type="text" class="form-control" id="headerSr" name="headerSr" 
                                                           value="<?php echo $invoiceSettings ? htmlspecialchars($invoiceSettings['HeaderSr']) : 'Sr'; ?>">
                                                </div>
                                            </div>
                                            
                                            <!-- Header Description -->
                                            <div class="col-md-8">
                                                <div class="form-group">
                                                    <label for="headerDescription">Description Column Header</label>
                                                    <input type="text" class="form-control" id="headerDescription" name="headerDescription" 
                                                           value="<?php echo $invoiceSettings ? htmlspecialchars($invoiceSettings['HeaderDescription']) : 'Goods & Service Description'; ?>">
                                                </div>
                                            </div>
                                            
                                            <!-- Header HSN -->
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="headerHSN">HSN Column Header</label>
                                                    <input type="text" class="form-control" id="headerHSN" name="headerHSN" 
                                                           value="<?php echo $invoiceSettings ? htmlspecialchars($invoiceSettings['HeaderHSN']) : 'HSN'; ?>">
                                                </div>
                                            </div>
                                            
                                            <!-- Header Quantity -->
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="headerQuantity">Quantity Column Header</label>
                                                    <input type="text" class="form-control" id="headerQuantity" name="headerQuantity" 
                                                           value="<?php echo $invoiceSettings ? htmlspecialchars($invoiceSettings['HeaderQuantity']) : 'Quantity'; ?>">
                                                </div>
                                            </div>
                                            
                                            <!-- Header MRP -->
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="headerMRP">MRP Column Header</label>
                                                    <input type="text" class="form-control" id="headerMRP" name="headerMRP" 
                                                           value="<?php echo $invoiceSettings ? htmlspecialchars($invoiceSettings['HeaderMRP']) : 'MRP'; ?>">
                                                </div>
                                            </div>
                                            
                                            <!-- Header Price -->
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="headerPrice">Price Column Header</label>
                                                    <input type="text" class="form-control" id="headerPrice" name="headerPrice" 
                                                           value="<?php echo $invoiceSettings ? htmlspecialchars($invoiceSettings['HeaderPrice']) : 'Price'; ?>">
                                                </div>
                                            </div>
                                            
                                            <!-- Header Discount -->
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="headerDiscount">Discount Column Header</label>
                                                    <input type="text" class="form-control" id="headerDiscount" name="headerDiscount" 
                                                           value="<?php echo $invoiceSettings ? htmlspecialchars($invoiceSettings['HeaderDiscount']) : 'Discount'; ?>">
                                                </div>
                                            </div>
                                            
                                            <!-- Header Basic Rate -->
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="headerBasicRate">Basic Rate Column Header</label>
                                                    <input type="text" class="form-control" id="headerBasicRate" name="headerBasicRate" 
                                                           value="<?php echo $invoiceSettings ? htmlspecialchars($invoiceSettings['HeaderBasicRate']) : 'Basic Rate'; ?>">
                                                </div>
                                            </div>
                                            
                                            <!-- Header Taxable -->
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="headerTaxable">Taxable Column Header</label>
                                                    <input type="text" class="form-control" id="headerTaxable" name="headerTaxable" 
                                                           value="<?php echo $invoiceSettings ? htmlspecialchars($invoiceSettings['HeaderTaxable']) : 'Taxable'; ?>">
                                                </div>
                                            </div>
                                            
                                            <!-- Header GST Percent -->
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="headerGSTPercent">GST % Column Header</label>
                                                    <input type="text" class="form-control" id="headerGSTPercent" name="headerGSTPercent" 
                                                           value="<?php echo $invoiceSettings ? htmlspecialchars($invoiceSettings['HeaderGSTPercent']) : '%'; ?>">
                                                </div>
                                            </div>
                                            
                                            <!-- Header GST Amount -->
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="headerGSTAmount">GST Amount Column Header</label>
                                                    <input type="text" class="form-control" id="headerGSTAmount" name="headerGSTAmount" 
                                                           value="<?php echo $invoiceSettings ? htmlspecialchars($invoiceSettings['HeaderGSTAmount']) : 'GST Amt.'; ?>">
                                                </div>
                                            </div>
                                            
                                            <!-- Header Total -->
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="headerTotal">Total Column Header</label>
                                                    <input type="text" class="form-control" id="headerTotal" name="headerTotal" 
                                                           value="<?php echo $invoiceSettings ? htmlspecialchars($invoiceSettings['HeaderTotal']) : 'Total'; ?>">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <hr class="my-4">
                                        
                                        <h5 class="text-primary mb-3">
                                            <i class="fas fa-cogs mr-2"></i>Invoice Sections
                                        </h5>
                                        
                                        <div class="row">
                                            <!-- Ship To -->
                                            <div class="col-md-6">
                                                <div class="custom-control custom-checkbox mb-3">
                                                    <input type="checkbox" class="custom-control-input" id="showShipTo" 
                                                           name="showShipTo" value="1"
                                                           <?php echo ($invoiceSettings && $invoiceSettings['ShowShipTo']) ? 'checked' : ''; ?>>
                                                    <label class="custom-control-label" for="showShipTo">Show "Ship To" Section</label>
                                                </div>
                                            </div>
                                            
                                            <!-- Other Details -->
                                            <div class="col-md-6">
                                                <div class="custom-control custom-checkbox mb-3">
                                                    <input type="checkbox" class="custom-control-input" id="showOtherDetails" 
                                                           name="showOtherDetails" value="1"
                                                           <?php echo ($invoiceSettings && $invoiceSettings['ShowOtherDetails']) ? 'checked' : ''; ?>>
                                                    <label class="custom-control-label" for="showOtherDetails">Show "Other Details" Section</label>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <hr class="my-4">
                                        
                                        <h5 class="text-primary mb-3">
                                            <i class="fas fa-file-alt mr-2"></i>Declaration
                                        </h5>
                                        
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="custom-control custom-checkbox mb-3">
                                                    <input type="checkbox" class="custom-control-input" id="showDeclaration" 
                                                           name="showDeclaration" value="1"
                                                           <?php echo ($invoiceSettings && $invoiceSettings['ShowDeclaration']) ? 'checked' : ''; ?>>
                                                    <label class="custom-control-label" for="showDeclaration">Show Declaration on Invoice</label>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-12">
                                                <div class="form-group">
                                                    <label for="declarationText">Declaration Text</label>
                                                    <textarea class="form-control" id="declarationText" name="declarationText" rows="3"><?php echo $invoiceSettings ? htmlspecialchars($invoiceSettings['DeclarationText']) : 'We declare that this invoice shows the actual price of the goods described and that all particulars are true and correct.'; ?></textarea>
                                                    <small class="form-text text-muted">This text will appear at the bottom of the invoice if enabled.</small>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-12">
                                                <div class="form-group">
                                                    <label for="footerText">Footer Text</label>
                                                    <textarea class="form-control" id="footerText" name="footerText" rows="4"><?php echo $invoiceSettings ? htmlspecialchars($invoiceSettings['FooterText']) : "1. Subject to Local jurisdiction\n2. Terms & conditions are subject to our trade policy\n3. Our risk & responsibility ceases after the delivery of goods.\n\nE. & O.E."; ?></textarea>
                                                    <small class="form-text text-muted">This footer text will appear in the declaration section of the invoice. The Show Declaration checkbox controls both declaration and footer visibility.</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <hr class="my-4">
                                        
                                        <h5 class="text-primary mb-3">
                                            <i class="fas fa-file-invoice mr-2"></i>Invoice Template
                                        </h5>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label for="gstInvoiceTemplate">GST Sales Invoice Template</label>
                                                    <select class="form-control" id="gstInvoiceTemplate" name="gstInvoiceTemplate">
                                                        <?php foreach ($gstInvoiceTemplates as $file => $label): ?>
                                                        <option value="<?php echo htmlspecialchars($file); ?>" <?php echo ($selectedGstTemplate === $file) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($label); ?>
                                                        </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <small class="form-text text-muted">This template is used for GST sales invoices.</small>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label for="nonGstInvoiceTemplate">Sales</label>
                                                    <select class="form-control" id="nonGstInvoiceTemplate" name="nonGstInvoiceTemplate">
                                                        <?php foreach ($nonGstInvoiceTemplates as $file => $label): ?>
                                                        <option value="<?php echo htmlspecialchars($file); ?>" <?php echo ($selectedNonGstTemplate === $file) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($label); ?>
                                                        </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <small class="form-text text-muted">This template is used when GST is not applied.</small>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="alert alert-info mt-2">
                                            <i class="fas fa-lightbulb mr-2"></i>
                                            <strong>Tip:</strong> GST and Sales templates switch automatically based on the sales type selected in the Sales module.
                                        </div>
                                        
                                        <div class="alert alert-info mt-3">
                                            <i class="fas fa-info-circle mr-2"></i>
                                            <strong>Note:</strong> Unchecking columns will hide them from the invoice printout. 
                                            Column headers can be customized as per your requirements. Signature will always be displayed if uploaded.
                                        </div>
                                        
                                        <div class="form-group mt-4">
                                            <button type="submit" class="btn btn-primary btn-lg btn-block">
                                                <i class="fas fa-save mr-2"></i>Save Invoice Settings
                                            </button>
                                        </div>
                                    </form>
                                </div>
                                <!-- End Invoice Settings Tab -->
                                
                                <!-- Invoice Font Settings Tab -->
                                <div class="tab-pane fade" id="font-settings" role="tabpanel">
                                    <?php include('invoice-font-settings.php'); ?>
                                </div>
                                <!-- End Invoice Font Settings Tab -->
                                
                            </div>
                            <!-- End Tab Content -->
                        </div>
                    </div>

                </div>
            </div>
            <?php include_once('../includes/footer.php');?>
        </div>
    </div>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="../logout.php">Logout</a>
                </div>
            </div>
        </div>
    </div>

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../js/sb-admin-2.min.js"></script>
    <script src="../js/modern-messagebox.js"></script>
    <script src="../js/messagebox-wrapper.js"></script>
    <?php renderQuickMenuScript(); ?>

    <script>
        $(document).ready(function() {
            // Toggle sidebar
            $('body').addClass('sidebar-toggled');
            $('.sidebar').addClass('toggled');
            
            // File upload validation
            $('input[type="file"]').on('change', async function() {
                const file = this.files[0];
                if (file) {
                    // Check file size (1024KB = 1MB)
                    if (file.size > 1024 * 1024) {
                        await MsgBox.alert('File size must be less than 1024KB (1MB)');
                        $(this).val('');
                        return false;
                    }
                }
            });
            
            // Auto-hide alerts
            setTimeout(function() {
                $('.alert').fadeOut();
            }, 5000);
        });
    </script>
</body>
</html>
