<?php
// stock.php

include 'db.php';

include 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $id = (int)($_POST['id'] ?? 0);

    $item_name = mysqli_real_escape_string($con, $_POST['item_name'] ?? '');
    $category = mysqli_real_escape_string($con, $_POST['category'] ?? '');
    $gross = (float)($_POST['gross_weight'] ?? 0);
    $net = (float)($_POST['net_weight'] ?? 0);
    $rate = (float)($_POST['rate'] ?? 0);
    $making_type = $_POST['making_type'] ?? 'percent';
    $making_value = (float)($_POST['making_value'] ?? 0);
    $stone_value = (float)($_POST['stone_value'] ?? 0);
    $hm_value = (float)($_POST['hm_value'] ?? 0);
    $total_value = (float)($_POST['total_value'] ?? 0);

    // Supplier
    $purchased_from = mysqli_real_escape_string($con, $_POST['purchased_from'] ?? '');
    $supplier_phone = mysqli_real_escape_string($con, $_POST['supplier_phone'] ?? '');
    $supplier_pan = mysqli_real_escape_string($con, $_POST['supplier_pan'] ?? '');
    $supplier_gst = mysqli_real_escape_string($con, $_POST['supplier_gst'] ?? '');
    $supplier_address = mysqli_real_escape_string($con, $_POST['supplier_address'] ?? '');
    $supplier_state = mysqli_real_escape_string($con, $_POST['supplier_state'] ?? '');
    $supplier_city = mysqli_real_escape_string($con, $_POST['supplier_city'] ?? '');
    $supplier_pincode = mysqli_real_escape_string($con, $_POST['supplier_pincode'] ?? '');

    // Payment
    $pay_upi = (float)($_POST['pay_upi'] ?? 0);
    $pay_cheque = (float)($_POST['pay_cheque'] ?? 0);
    $pay_metal = (float)($_POST['pay_metal'] ?? 0);
    $pay_cash = (float)($_POST['pay_cash'] ?? 0);
    $pay_card = (float)($_POST['pay_card'] ?? 0);

    /* ---------- FINANCIAL YEAR ---------- */
    $currentYear  = date('Y');
    $currentMonth = date('n'); // 1..12

    if ($currentMonth >= 4) {
        $startYear = $currentYear;
        $endYear   = $currentYear + 1;
    } else {
        $startYear = $currentYear - 1;
        $endYear   = $currentYear;
    }

    $fyStart = substr($startYear, -2); // e.g., 25
    $fyEnd   = substr($endYear, -2);   // e.g., 26

    /* ---------- INVOICE NUMBER ---------- */
    $invoice_no = mysqli_real_escape_string($con, $_POST['invoice_no'] ?? '');

    if (empty($invoice_no)) {
        $usedNumbers = [];
        $res = mysqli_query($con, "
            SELECT invoice_no FROM jewellery_stock 
            WHERE invoice_no LIKE 'RP/{$fyStart}/{$fyEnd}/%'
        ");
        while ($row = mysqli_fetch_assoc($res)) {
            $parts = explode('/', $row['invoice_no']);
            $seq = (int) end($parts);
            $usedNumbers[] = $seq;
        }

        $nextNumber = 1;
        while (in_array($nextNumber, $usedNumbers)) {
            $nextNumber++;
        }

        $invoice_no = "RP/{$fyStart}/{$fyEnd}/" . str_pad($nextNumber, 2, '0', STR_PAD_LEFT);
    }

    if ($id > 0) {
        // ===== UPDATE STOCK =====
        mysqli_query($con, "
            UPDATE jewellery_stock SET
                invoice_no='$invoice_no',
                item_name='$item_name',
                category='$category',
                gross_weight='$gross',
                net_weight='$net',
                rate='$rate',
                making_type='$making_type',
                making_value='$making_value',
                stone_value='$stone_value',
                hm_value='$hm_value',
                total_value='$total_value',
                purchased_from='$purchased_from',
                supplier_phone='$supplier_phone',
                supplier_pan='$supplier_pan',
                supplier_gst='$supplier_gst',
                supplier_address='$supplier_address',
                supplier_state='$supplier_state',
                supplier_city='$supplier_city',
                supplier_pincode='$supplier_pincode',
                pay_upi='$pay_upi',
                pay_cheque='$pay_cheque',
                pay_metal='$pay_metal',
                pay_cash='$pay_cash',
                pay_card='$pay_card'
            WHERE id='$id'
        ");
    } else {
        // ===== INSERT NEW STOCK =====
        mysqli_query($con, "
            INSERT INTO jewellery_stock
            (invoice_no, item_name, category, gross_weight, net_weight, rate, making_type, making_value, stone_value, hm_value, total_value,
            purchased_from, supplier_phone, supplier_pan, supplier_gst, supplier_address, supplier_state, supplier_city, supplier_pincode,
            pay_upi, pay_cheque, pay_metal, pay_cash, pay_card)
            VALUES
            ('$invoice_no', '$item_name', '$category', '$gross', '$net', '$rate', '$making_type', '$making_value', '$stone_value', '$hm_value', '$total_value',
            '$purchased_from', '$supplier_phone', '$supplier_pan', '$supplier_gst', '$supplier_address', '$supplier_state', '$supplier_city', '$supplier_pincode',
            '$pay_upi', '$pay_cheque', '$pay_metal', '$pay_cash', '$pay_card')
        ");
    }

    header("Location: stock.php");
    exit;
}

// ---------- HANDLE DELETE ----------
if (isset($_GET['delete'])) {
    $del_id = (int)$_GET['delete'];
    mysqli_query($con, "DELETE FROM jewellery_stock WHERE id='$del_id'");
    header("Location: stock.php");
    exit;
}

// ---------- FETCH DATA FOR EDIT ----------
$edit = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $res = mysqli_query($con, "SELECT * FROM jewellery_stock WHERE id='$edit_id'");
    $edit = mysqli_fetch_assoc($res);
}

// ---------- FETCH ALL STOCK ----------
$stocks = mysqli_query($con, "SELECT * FROM jewellery_stock ORDER BY added_on DESC");

// ---------- INCLUDE HEADER ----------
$title = "Jewellery Stock";
include 'include/header.php';
?>

<!-- ===== HTML FORM & STOCK TABLE ===== -->
<div id="page-wrapper">
    <div id="page-inner">
        <h3><?php echo $edit ? 'Edit Jewellery / Gold' : 'Add Jewellery / Gold'; ?></h3>

        <form id="stockForm" method="post" action="stock.php">
            <input type="hidden" name="id" value="<?php echo $edit['id'] ?? 0; ?>">

            <div class="col-md-3">
                <input type="text" name="invoice_no" class="form-control" placeholder="Invoice No"
                    value="<?php echo $edit['invoice_no'] ?? ''; ?>" readonly>
            </div>

            <!-- Item Details -->
            <div class="row g-2 mt-2">
                <div class="col-md-3"><input type="text" name="item_name" placeholder="Item Name" class="form-control"
                        f value="<?php echo $edit['item_name'] ?? ''; ?>"></div>
                <div class="col-md-3">
                    <select name="category" class="form-control"  >
                        <option value="">Select Category</option>
                        <option value="Gold" <?php if(($edit['category'] ?? '')=='Gold') echo 'selected'; ?>>Gold
                        </option>
                        <option value="Silver" <?php if(($edit['category'] ?? '')=='Silver') echo 'selected'; ?>>Silver
                        </option>
                        <option value="Diamond" <?php if(($edit['category'] ?? '')=='Diamond') echo 'selected'; ?>>
                            Diamond</option>
                    </select>
                </div>
                <div class="col-md-2"><input type="number" step="0.001" name="gross_weight" placeholder="Gross Weight"
                        class="form-control"   value="<?php echo $edit['gross_weight'] ?? ''; ?>"></div>
                <div class="col-md-2"><input type="number" step="0.001" name="net_weight" placeholder="Net Weight"
                        class="form-control"   value="<?php echo $edit['net_weight'] ?? ''; ?>"></div>
                <div class="col-md-2"><input type="number" step="0.01" name="rate" placeholder="Rate"
                        class="form-control"   value="<?php echo $edit['rate'] ?? ''; ?>"></div>
            </div>

            <!-- Making, Stone, HM, Total -->
            <div class="row g-2 mt-2">
                <div class="col-md-2">
                    <select name="making_type" class="form-control">
                        <option value="percent" <?php if(($edit['making_type'] ?? '')=='percent') echo 'selected'; ?>>
                            Percent</option>
                        <option value="fixed" <?php if(($edit['making_type'] ?? '')=='fixed') echo 'selected'; ?>>Fixed
                        </option>
                    </select>
                </div>
                <div class="col-md-2"><input type="number" step="0.01" name="making_value" placeholder="Making Value"
                        class="form-control" value="<?php echo $edit['making_value'] ?? ''; ?>"></div>
                <div class="col-md-2"><input type="number" step="0.01" name="stone_value" placeholder="Stone Value"
                        class="form-control" value="<?php echo $edit['stone_value'] ?? ''; ?>"></div>
                <div class="col-md-2"><input type="number" step="0.01" name="hm_value" placeholder="HM Value"
                        class="form-control" value="<?php echo $edit['hm_value'] ?? ''; ?>"></div>
                <div class="col-md-2"><input type="number" step="0.01" name="total_value" placeholder="Total Value"
                        class="form-control" readonly value="<?php echo $edit['total_value'] ?? ''; ?>"></div>
            </div>

            <!-- Supplier Details -->
            <h5 class="mt-3">Supplier Details</h5>
            <div class="row g-2">
                <div class="col-md-3"><input type="text" name="purchased_from" placeholder="Supplier Name"
                        class="form-control" value="<?php echo $edit['purchased_from'] ?? ''; ?>"></div>
                <div class="col-md-3"><input type="text" name="supplier_phone" placeholder="Phone" class="form-control"
                        value="<?php echo $edit['supplier_phone'] ?? ''; ?>"></div>
                <div class="col-md-3"><input type="text" name="supplier_pan" placeholder="PAN No" class="form-control"
                        value="<?php echo $edit['supplier_pan'] ?? ''; ?>"></div>
                <div class="col-md-3"><input type="text" name="supplier_gst" placeholder="GST No" class="form-control"
                        value="<?php echo $edit['supplier_gst'] ?? ''; ?>"></div>
                <div class="col-md-6"><input type="text" name="supplier_address" placeholder="Address"
                        class="form-control" value="<?php echo $edit['supplier_address'] ?? ''; ?>"></div>
                <div class="col-md-2"><input class="form-control" name="supplier_state" placeholder="State"
                        list="stateList" value="<?php echo $edit['supplier_state'] ?? ''; ?>">
                    <datalist id="stateList">
                        <option value="Andhra Pradesh">
                        <option value="Arunachal Pradesh">
                        <option value="Assam">
                        <option value="Bihar">
                        <option value="Chhattisgarh">
                        <option value="Goa">
                        <option value="Gujarat">
                        <option value="Haryana">
                        <option value="Himachal Pradesh">
                        <option value="Jharkhand">
                        <option value="Karnataka">
                        <option value="Kerala">
                        <option value="Madhya Pradesh">
                        <option value="Maharashtra">
                        <option value="Odisha">
                        <option value="Punjab">
                        <option value="Rajasthan">
                        <option value="Tamil Nadu">
                        <option value="Telangana">
                        <option value="Uttar Pradesh">
                        <option value="West Bengal">
                    </datalist>
                </div>
                <div class="col-md-2"><input type="text" name="supplier_city" placeholder="City" class="form-control"
                        value="<?php echo $edit['supplier_city'] ?? ''; ?>"></div>
                <div class="col-md-2"><input type="text" name="supplier_pincode" placeholder="Pincode"
                        class="form-control" value="<?php echo $edit['supplier_pincode'] ?? ''; ?>"></div>
            </div>

            <!-- Payment Details -->
            <h5 class="border-bottom pb-2 mt-4">Payment Details</h5>
            <div class="row g-2 text-center">
                <div class="col-md-2"><label>UPI</label>
                    <input class="form-control text-end pay-input" name="pay_upi"
                        value="<?php echo $edit['pay_upi'] ?? ''; ?>">
                </div>
                <div class="col-md-2"><label>Cheque</label>
                    <input class="form-control text-end pay-input" name="pay_cheque"
                        value="<?php echo $edit['pay_cheque'] ?? ''; ?>">
                </div>
                <div class="col-md-2"><label>Metal</label>
                    <input class="form-control text-end pay-input" name="pay_metal"
                        value="<?php echo $edit['pay_metal'] ?? ''; ?>">
                </div>
                <div class="col-md-2"><label>Cash</label>
                    <input class="form-control text-end pay-input" name="pay_cash"
                        value="<?php echo $edit['pay_cash'] ?? ''; ?>">
                </div>
                <div class="col-md-2"><label>Card</label>
                    <input class="form-control text-end pay-input" name="pay_card"
                        value="<?php echo $edit['pay_card'] ?? ''; ?>">
                </div>
                <div class="col-md-2"><label>Dues</label>
                    <input class="form-control text-end" readonly id="duesBox">
                </div>
            </div>

            <div class="mt-4">
                <button type="submit" class="btn btn-success">
                    <?php echo $edit ? 'Update Stock' : 'Add Stock'; ?>
                </button>
                <?php if($edit): ?>
                <a href="stock.php" class="btn btn-warning">Cancel</a>
                <?php endif; ?>
            </div>
        </form>

        <hr>
        <h4>Stock List</h4>
        <div class="row mb-2">
            <div class="col-md-6"><input type="text" id="search" class="form-control" placeholder="Search ..."></div>
        </div>

        <table class="table table-bordered table-striped mt-2" id="invoiceTable">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Item</th>
                    <th>Category</th>
                    <th>Net Weight</th>
                    <th>Rate</th>
                    <th>Total</th>
                    <th>Supplier</th>
                    <th>Customer</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php while($row = mysqli_fetch_assoc($stocks)): ?>
                <tr>
                    <td><?php echo $row['id']; ?></td>
                    <td><?php echo $row['item_name']; ?></td>
                    <td><?php echo $row['category']; ?></td>
                    <td><?php echo $row['net_weight']; ?></td>
                    <td><?php echo $row['rate']; ?></td>
                    <td><?php echo $row['total_value']; ?></td>
                    <td><?php echo $row['purchased_from']; ?></td>
                    <td><?php echo $row['sold_to']; ?></td>
                    <td>
                        <a href="stock_invoice.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-info"
                            target="_blank">
                            <i class="fa fa-eye"></i>
                        </a>
                        <!-- <a href="stock.php?edit=<?php echo $row['id']; ?>" class="btn btn-sm btn-warning">Edit</a> -->
                        <a href="stock.php?delete=<?php echo $row['id']; ?>"
                            onclick="return confirm('Delete this item?');" class="btn btn-sm btn-danger">Delete</a>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>
<script>
// ENTER KEY → NEXT INPUT FIELD
$('#stockForm').on('keydown', 'input, select', function(e) {

    if (e.key === "Enter") {

        e.preventDefault(); // form submit rok do

        let inputs = $('#stockForm')
            .find('input, select, textarea')
            .filter(':visible:not([readonly])');

        let index = inputs.index(this);

        if (index > -1 && index + 1 < inputs.length) {
            inputs.eq(index + 1).focus();
        } else {
            // Agar last field hai to submit karo
            $('#stockForm').submit();
        }
    }

});
</script>
<!-- ===== JS: Total & Dues Calculation ===== -->
<script>
$('#stockForm input, #stockForm select').on('input change', function() {
    let net = parseFloat($('[name="net_weight"]').val()) || 0;
    let rate = parseFloat($('[name="rate"]').val()) || 0;
    let makingType = $('[name="making_type"]').val();
    let making = parseFloat($('[name="making_value"]').val()) || 0;
    let stone = parseFloat($('[name="stone_value"]').val()) || 0;
    let hm = parseFloat($('[name="hm_value"]').val()) || 0;

    let metal = net * rate;
    let makingCalc = makingType === 'percent' ? (metal * making / 100) : making;
    let total = metal + makingCalc + stone + hm;

    $('[name="total_value"]').val(total.toFixed(2));

    let upi = parseFloat($('[name="pay_upi"]').val()) || 0;
    let cheque = parseFloat($('[name="pay_cheque"]').val()) || 0;
    let metalPay = parseFloat($('[name="pay_metal"]').val()) || 0;
    let cash = parseFloat($('[name="pay_cash"]').val()) || 0;
    let card = parseFloat($('[name="pay_card"]').val()) || 0;

    let paid = upi + cheque + metalPay + cash + card;
    let dues = total - paid;

    $('#duesBox').val(dues.toFixed(2));
});

// Search filter
document.getElementById('search').addEventListener('keyup', function() {
    let value = this.value.toLowerCase();
    document.querySelectorAll('#invoiceTable tbody tr').forEach(tr => {
        tr.style.display = tr.innerText.toLowerCase().includes(value) ? '' : 'none';
    });
});

// Run on page load
$(document).ready(function() {
    $('#stockForm input, #stockForm select').trigger('input');
});
</script>

<?php include 'include/footer.php'; ?>