<?php
ob_start();
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
require("includes/config.php");
require("includes/function.php");
require("includes/check_permission.php");

$formname = 'Product';
$maindb = 'product';
$printfile = 'product_print.php';
$file = 'product.php';
$keyfld = 'id';
$keycond = "";

$zdb = $_SESSION["zdbyear_" . $dbname];
$compcd = $_SESSION["comp_" . $dbname];
$usertype = $_SESSION["usertype_" . $dbname];

mysqli_select_db($conn, $zdb);

// ── Defensive auto-migrate: ensure brand column exists on product ──────────
foreach ([
    'brand'      => "VARCHAR(100) NOT NULL DEFAULT ''",
    'gstpercent' => "DOUBLE NOT NULL DEFAULT 0",
    'hsncode'    => "VARCHAR(20) NOT NULL DEFAULT ''",
] as $col => $def) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `product` LIKE '$col'");
    if ($chk && mysqli_num_rows($chk) == 0)
        mysqli_query($conn, "ALTER TABLE `product` ADD COLUMN `$col` $def");
}

include("includes/vouchno_generate.php");
include("includes/prev_next.php");

$uploaddir = __DIR__ . '/uploads/products/';
$uploadurl = 'uploads/products/';
if (!is_dir($uploaddir)) {
    mkdir($uploaddir, 0755, true);
}

const PRODUCT_IMAGE_MAXSIZE = 102400; // 100 KB
// ── POST: Insert / Update ────────────────────────────────────────────────────
if (isset($_POST["submit"])) {
    $name = mysqli_real_escape_string($conn, trim($_POST["name"]));
    $brand = mysqli_real_escape_string($conn, trim($_POST["brand"]));
    $cost = mysqli_real_escape_string($conn, trim($_POST["cost"]));
    $amount = mysqli_real_escape_string($conn, trim($_POST["amount"]));
    $unit = mysqli_real_escape_string($conn, trim($_POST["unit"]));
    $unitpercarton = mysqli_real_escape_string($conn, trim($_POST["unitpercarton"]));
    $gstpercent = mysqli_real_escape_string($conn, trim($_POST["gstpercent"] ?? ''));
    $hsncode = mysqli_real_escape_string($conn, trim($_POST["hsncode"] ?? ''));

    if ($cost == '')
        $cost = 0;
    if ($amount == '')
        $amount = 0;
    if ($unitpercarton == '')
        $unitpercarton = 0;
    if ($gstpercent == '')
        $gstpercent = 0;

    $a = 1;

    if ($name == '') {
        $a = 0;
        browse("Name Cannot Be Empty");
        header("refresh:1; url=$file?mode=last");
    }

    if ($a == 1) {
        $chkdup = mysqli_query($conn, "SELECT `id` FROM `$maindb` WHERE `name`='$name' AND `id`!='$qvouch'") or die(mysqli_error($conn));
        if (mysqli_num_rows($chkdup) > 0) {
            $a = 0;
            browse("Product With This Name Already Exists");
            header("refresh:1; url=$file?mode=last");
        }
    }

    // ── Image upload (optional, max 100KB) ──────────────────────────────────
    $imagename = '';
    if ($a == 1 && isset($_FILES['image']) && $_FILES['image']['error'] != UPLOAD_ERR_NO_FILE) {
        $img = $_FILES['image'];

        if ($img['error'] != UPLOAD_ERR_OK) {
            $a = 0;
            browse("Image Upload Failed");
            header("refresh:1; url=$file?mode=last");
        } elseif ($img['size'] > PRODUCT_IMAGE_MAXSIZE) {
            $a = 0;
            browse("Image Size Must Be Up To 100 KB");
            header("refresh:1; url=$file?mode=last");
        } else {
            $allowedExt = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', 'webp' => 'image/webp'];
            $ext = strtolower(pathinfo($img['name'], PATHINFO_EXTENSION));
            $mime = mime_content_type($img['tmp_name']);

            if (!isset($allowedExt[$ext]) || $mime != $allowedExt[$ext]) {
                $a = 0;
                browse("Only JPG, PNG, GIF or WEBP Images Are Allowed");
                header("refresh:1; url=$file?mode=last");
            } else {
                $imagename = 'prod_' . $qvouch . '_' . time() . '.' . $ext;
                if (!move_uploaded_file($img['tmp_name'], $uploaddir . $imagename)) {
                    $a = 0;
                    browse("Could Not Save Uploaded Image");
                    header("refresh:1; url=$file?mode=last");
                    $imagename = '';
                }
            }
        }
    }

    if ($a == 1) {
        $audituser = mysqli_real_escape_string($conn, audituser());

        if ($addflag == 1) {
            mysqli_query($conn, "INSERT INTO `$maindb`
                (`id`,`name`,`brand`,`cost`,`amount`,`unit`,`unitpercarton`,`gstpercent`,`hsncode`,`image`,`adduser`,`adddate`,`addtime`)
                VALUES
                ('$qvouch','$name','$brand','$cost','$amount','$unit','$unitpercarton','$gstpercent','$hsncode','$imagename','$audituser',CURDATE(),CURTIME())")
                    or die(mysqli_error($conn));
            insmess();
            header("refresh:1; url=$file?$keyfld=$qvouch&mode=edit");
        } else {
            $imagesql = '';
            if ($imagename != '') {
                // remove old image file if replacing
                $oldimg = mysqli_query($conn, "SELECT `image` FROM `$maindb` WHERE `id`='$qvouch'") or die(mysqli_error($conn));
                $oldrow = mysqli_fetch_assoc($oldimg);
                if ($oldrow && $oldrow['image'] != '' && file_exists($uploaddir . $oldrow['image'])) {
                    unlink($uploaddir . $oldrow['image']);
                }
                $imagesql = ", `image`='$imagename'";
            }

            mysqli_query($conn, "UPDATE `$maindb` SET
                `name`='$name', `brand`='$brand', `cost`='$cost', `amount`='$amount',
                `unit`='$unit', `unitpercarton`='$unitpercarton', `gstpercent`='$gstpercent',
                `hsncode`='$hsncode'$imagesql,
                `edituser`='$audituser', `editdate`=CURDATE(), `edittime`=CURTIME()
                WHERE `id`='$qvouch'")
                    or die(mysqli_error($conn));
            updmess();
            header("refresh:1; url=$file?$keyfld=$qvouch&mode=edit");
        }
    }
}

// ── Fetch record ─────────────────────────────────────────────────────────────
$get = [];
if ($addflag != 1 && $qvouch > 0) {
    $result = mysqli_query($conn, "SELECT * FROM `$maindb` WHERE `$keyfld`='$qvouch'") or die(mysqli_error($conn));
    $get = mysqli_fetch_array($result);
    if (!$get)
        $get = [];
} elseif ($addflag == 1 && isset($_GET['repeat'])) {
    // ── "Repeat" flow: user is adding a new colour/size variant of a product
    //    they just saved. The Repeat button carries every field — including
    //    Name — over via querystring, so this brand-new record starts
    //    pre-filled with the same name (cursor placed at the end, see the
    //    script block below) ready for them to just type the extra colour/
    //    size word straight onto it and Save. Values only ever feed into
    //    `fv()` (htmlspecialchars) for display here; the actual save on
    //    submit re-reads fresh from $_POST, same validation as any other
    //    add (including the duplicate-name check below), so this can't be
    //    used to bypass anything. ─────────────────────────────────────
    foreach (['name', 'brand', 'cost', 'amount', 'gstpercent', 'hsncode', 'unit', 'unitpercarton'] as $rf) {
        if (isset($_GET[$rf])) $get[$rf] = $_GET[$rf];
    }
}

// ── DELETE ───────────────────────────────────────────────────────────────────
if (isset($_GET["delete"])) {
    if ($usertype != 1) { header("refresh:1; url=$file?mode=last"); exit; } // admin-only delete guard
    $delimg = mysqli_query($conn, "SELECT `image` FROM `$maindb` WHERE `$keyfld`='$qvouch'") or die(mysqli_error($conn));
    $delrow = mysqli_fetch_assoc($delimg);
    if ($delrow && $delrow['image'] != '' && file_exists($uploaddir . $delrow['image'])) {
        unlink($uploaddir . $delrow['image']);
    }
    mysqli_query($conn, "DELETE FROM `$maindb` WHERE `$keyfld`='$qvouch'") or die(mysqli_error($conn));
    delmess();
    header("refresh:1; url=$file?mode=last");
    exit;
}

// Unit list for dropdown
$unitList = mysqli_query($conn, "SELECT `code`,`name` FROM `unit` ORDER BY `name`") or die(mysqli_error($conn));
$brandList = mysqli_query($conn, "SELECT `code`,`name` FROM `brand` ORDER BY `name`") or die(mysqli_error($conn));

// Helper: get value safely
function fv($get, $key, $default = '') {
    return isset($get[$key]) ? htmlspecialchars($get[$key]) : $default;
}

include("includes/linkshead.php");
?>
<link rel="stylesheet" href="assets/css/master-form.css">

<body>
    <form action="" method="POST" enctype="multipart/form-data">
        <div class="sim-card">

            <!-- Header -->
            <div class="sim-card-header">
                <h2><i class="fa fa-box" style="color:#3b82f6;margin-right:8px;font-size:14px;"></i><?php echo $formname; ?></h2>
                <span class="sim-badge">Code: <?php echo $qvouch > 0 ? $qvouch : 'New'; ?></span>
            </div>

            <div class="sim-body">

                <!-- Name -->
                <div class="fr-2">
                    <div class="fl">
                        <span class="lbl">Name <span style="color:#ef4444;">*</span></span>
                        <input type="text" name="name" class="finp form focusfield required-star" required
                               value="<?php echo fv($get, 'name'); ?>">
                    </div>
                </div>

                <!-- Brand | Category -->
                <div class="fr-2">
                    <div class="fl">
                        <span class="lbl">Brand</span>
                        <select name="brand" class="finp form">
                            <option value="">-- Select Brand --</option>
                            <?php
                            mysqli_data_seek($brandList, 0);
                            while ($urow = mysqli_fetch_assoc($brandList)):
                            ?>
                                <option value="<?php echo $urow['code']; ?>"
                                    <?php echo ((string)fv($get,'brand') == (string)$urow['code']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($urow['name']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                </div>

                <!-- Cost | Amount -->
                <div class="fr-2">
                    <div class="fl">
                        <span class="lbl">Cost</span>
                        <input type="number" step="0.01" name="cost" class="finp form no-arrows"
                               value="<?php echo fv($get, 'cost', '0'); ?>">
                    </div>
                </div>
                <div class="fr-2">
                    <div class="fl">
                        <span class="lbl">Rate</span>
                        <input type="number" step="0.01" name="amount" class="finp form no-arrows"
                               value="<?php echo fv($get, 'amount', '0'); ?>">
                    </div>
                </div>

                <!-- GST % | HSN Code -->
                <div class="fr-2">
                    <div class="fl">
                        <span class="lbl">GST %</span>
                        <input type="number" step="0.01" min="0" max="100" name="gstpercent" class="finp form no-arrows"
                               value="<?php echo fv($get, 'gstpercent', '0'); ?>">
                    </div>
                </div>
                <div class="fr-2">
                    <div class="fl">
                        <span class="lbl">HSN Code</span>
                        <input type="text" name="hsncode" maxlength="20" class="finp form"
                               value="<?php echo fv($get, 'hsncode'); ?>">
                    </div>
                </div>

                <!-- Unit | Pcs Per Unit -->
                <div class="fr-2">
                    <div class="fl">
                        <span class="lbl">Unit</span>
                        <select name="unit" class="finp form">
                            <option value="">-- Select Unit --</option>
                            <?php
                            mysqli_data_seek($unitList, 0);
                            while ($urow = mysqli_fetch_assoc($unitList)):
                                ?>
                                <option value="<?php echo htmlspecialchars($urow['name']); ?>"
                                        <?php echo (fv($get, 'unit') == $urow['name']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($urow['name']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                </div>
                <div class="fr-2">
                    <div class="fl">
                        <span class="lbl">Pcs Per Carton</span>
                        <input type="number" step="0.01" name="unitpercarton" class="finp form no-arrows"
                               value="<?php echo fv($get, 'unitpercarton', '0'); ?>">
                    </div>
                </div>

                <!-- Image -->
                <div class="fr-2">
                    <div class="fl" style="align-items:flex-start;">
                        <span class="lbl" style="padding-top:7px;">Image</span>
                        <div style="flex:1;display:flex;flex-direction:column;gap:6px;">
                            <input type="file" name="image" accept=".jpg,.jpeg,.png,.gif,.webp" class="finp form">
                            <span style="font-size:11px;color:#94a3b8;">Max size 100 KB. JPG, PNG, GIF or WEBP.</span>
                            <?php if (fv($get, 'image') != ''): ?>
                                <img src="uploads/products/<?php echo fv($get, 'image'); ?>" alt="Product Image"
                                     style="max-width:120px;max-height:120px;border:1px solid #e2e8f0;border-radius:6px;object-fit:cover;">
                                 <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Audit Info -->
                <?php if ($qvouch > 0 && (fv($get, 'adduser') != '' || fv($get, 'edituser') != '')): ?>
                    <div class="audit-info">
                        <?php if (fv($get, 'adduser') != ''): ?>
                            <span><i class="fa fa-plus-circle"></i> Added by <b><?php echo fv($get, 'adduser'); ?></b> on <?php echo fv($get, 'adddate'); ?> <?php echo fv($get, 'addtime'); ?></span>
                        <?php endif; ?>
                        <?php if (fv($get, 'edituser') != ''): ?>
                            <span><i class="fa fa-pen"></i> Last edited by <b><?php echo fv($get, 'edituser'); ?></b> on <?php echo fv($get, 'editdate'); ?> <?php echo fv($get, 'edittime'); ?></span>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>

            </div><!-- /sim-body -->

            <!-- Action Button Bar -->
            <?php include("includes/buttons.php"); ?>

        </div><!-- /sim-card -->
    </form>


    <!-- ── Search Modal ─────────────────────────────────────────────────────────── -->
    <div id="searchModal" class="srch-overlay">
        <div class="srch-dialog">

            <!-- Modal header -->
            <div class="srch-header">
                <span class="srch-title">
                    <i class="fa fa-search" style="color:#db2777;margin-right:8px;"></i>Search <?php echo $formname; ?>
                </span>
                <button type="button" class="srch-close"
                        onclick="document.getElementById('searchModal').style.display = 'none'">&times;</button>
            </div>

            <!-- Filter row -->
            <div class="srch-filterbar">
                <div>
                    <label class="srch-label">Field</label>
                    <select id="srchField" class="srch-ctl">
                        <option value="id">ID</option>
                        <option value="name" selected>Name</option>
                        <option value="cost">Cost</option>
                        <option value="amount">Amount</option>
                        <option value="unit">Unit</option>
                        <option value="unitpercarton">Pcs/Unit</option>
                        <option value="gstpercent">GST %</option>
                        <option value="hsncode">HSN Code</option>
                    </select>
                </div>
                <div>
                    <label class="srch-label">Operator</label>
                    <select id="srchOperator" class="srch-ctl">
                        <option value="like" selected>Like</option>
                        <option value="=">=</option>
                    </select>
                </div>
                <div>
                    <label class="srch-label">Sort By</label>
                    <select id="srchSortField" class="srch-ctl">
                        <option value="id">ID</option>
                        <option value="name" selected>Name</option>
                        <option value="cost">Cost</option>
                        <option value="amount">Amount</option>
                        <option value="unit">Unit</option>
                        <option value="unitpercarton">Pcs/Unit</option>
                        <option value="gstpercent">GST %</option>
                        <option value="hsncode">HSN Code</option>
                    </select>
                </div>
                <div>
                    <label class="srch-label">Order</label>
                    <select id="srchSortOrder" class="srch-ctl">
                        <option value="asc" selected>Asc</option>
                        <option value="desc">Desc</option>
                    </select>
                </div>
                <div class="srch-grow">
                    <label class="srch-label">Search</label>
                    <input type="text" id="srchInput" class="srch-input" placeholder="Type to search...">
                </div>
                <div>
                    <button type="button" id="srchGoBtn" class="srch-go-btn">
                        <i class="fa fa-search"></i> Search
                    </button>
                </div>
            </div>

            <!-- Table -->
            <div class="srch-tablewrap">
                <table class="srch-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Cost</th>
                            <th>Amount</th>
                            <th>Unit</th>
                            <th>Pcs/Unit</th>
                            <th>GST %</th>
                            <th>HSN Code</th>
                        </tr>
                    </thead>
                    <tbody id="srchBody"></tbody>
                </table>
            </div>

            <!-- Pagination footer -->
            <div class="srch-pagination">
                <button type="button" id="srchPrevBtn" class="srch-page-btn srch-page-btn--prev">
                    <i class="fa fa-chevron-left"></i> Previous
                </button>
                <span id="srchPageInfo" class="srch-page-info"></span>
                <button type="button" id="srchNextBtn" class="srch-page-btn srch-page-btn--next">
                    Next <i class="fa fa-chevron-right"></i>
                </button>
            </div>

        </div>
    </div>

    <script>
        // ── Search modal (AJAX) ──────────────────────────────────────────────────────
        var srchPage = 1;
        var srchPages = 1;

        function srchLoad(page) {
            srchPage = page;
            $.post('includes/product_search.php', {
                file: '<?php echo $file; ?>',
                keyfld: '<?php echo $keyfld; ?>',
                field: $('#srchField').val(),
                operator: $('#srchOperator').val(),
                sortfield: $('#srchSortField').val(),
                sortorder: $('#srchSortOrder').val(),
                search: $('#srchInput').val(),
                page: page
            }, function (data) {
                $('#srchBody').html(data.rows);
                srchPage = data.page;
                srchPages = data.pages;
                $('#srchPageInfo').text('Page ' + srchPage + ' of ' + srchPages + ' (' + data.total + ' records)');
                $('#srchPrevBtn').prop('disabled', srchPage <= 1).css('opacity', srchPage <= 1 ? .5 : 1);
                $('#srchNextBtn').prop('disabled', srchPage >= srchPages).css('opacity', srchPage >= srchPages ? .5 : 1);
            }, 'json');
        }

        $('#srchGoBtn').on('click', function () {
            srchLoad(1);
        });
        $('#srchInput').on('keyup', function (e) {
            if (e.key === 'Enter')
                srchLoad(1);
        });
        $('#srchPrevBtn').on('click', function () {
            if (srchPage > 1)
                srchLoad(srchPage - 1);
        });
        $('#srchNextBtn').on('click', function () {
            if (srchPage < srchPages)
                srchLoad(srchPage + 1);
        });

        // Close on backdrop
        document.getElementById('searchModal').addEventListener('click', function (e) {
            if (e.target === this)
                this.style.display = 'none';
        });

        // ── Repeat button: lets you spin off a colour/size variant of the
        // currently-viewed product without retyping Name/Brand/Cost/Rate/
        // GST/HSN/Unit/Pcs-per-Carton. Only makes sense once a saved record
        // is on screen, so it's injected with the exact same visibility as
        // Print (hidden in Add mode) and lives outside includes/buttons.php
        // since this is product-only, not a change to every master's button
        // bar.
        (function () {
            var repeatBtn = $(
                '<button id="hrepeat" type="button" class="abtn" data-tip="Repeat as New" ' +
                'style="display:<?php echo $printdisabled; ?>;background:#0891b2;">' +
                '<i class="fa fa-clone"></i></button>'
            );
            repeatBtn.on('click', function () {
                var params = new URLSearchParams();
                params.set('mode', 'true');
                params.set('repeat', '1');
                ['name', 'brand', 'cost', 'amount', 'gstpercent', 'hsncode', 'unit', 'unitpercarton'].forEach(function (f) {
                    var el = document.querySelector('[name="' + f + '"]');
                    if (el) params.set(f, el.value || '');
                });
                window.location.href = '<?php echo $file; ?>?' + params.toString();
            });
            var $printBtn = $('#hprint');
            if ($printBtn.length) { $printBtn.after(repeatBtn); } else { $('.btn-bar').append(repeatBtn); }
        })();

        <?php if ($addflag == 1 && isset($_GET['repeat'])): ?>
        // Landed here via Repeat: the global focusFirstField() (linkshead.php)
        // already focused + select-all'd the Name field, which would wipe the
        // carried-over name the instant the user starts typing. Put the
        // cursor at the end instead, so typing appends (e.g. "T-Shirt" ->
        // "T-Shirt Red") rather than replacing it. Runs after that handler
        // since this script block is registered later in the page.
        $(function () {
            var nameFld = document.querySelector('input[name="name"]');
            if (nameFld) {
                var len = nameFld.value.length;
                nameFld.focus();
                nameFld.setSelectionRange(len, len);
            }
        });
        <?php endif; ?>

        // Validate image size (100KB) before submit
        document.querySelector('input[name="image"]') && document.querySelector('input[name="image"]').addEventListener('change', function () {
            if (this.files.length > 0 && this.files[0].size > 102400) {
                Swal.fire({icon: 'warning', title: 'Notice', text: 'Image Size Must Be Up To 100 KB', confirmButtonColor: '#2563eb'});
                this.value = '';
            }
        });
        // Load + focus search input when modal opens
        document.getElementById('hsearch') && document.getElementById('hsearch').addEventListener('click', function () {
            srchLoad(1);
            setTimeout(function () {
                document.getElementById('srchInput').focus();
            }, 60);
        });
    </script>

    <?php include("includes/linksfoot.php"); ?>
</body>
</html>
