<?php
// Enable error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include 'db.php';
include 'auth_check.php';

$msg = "";

// Form processing
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $invoice = $_POST['invoice_number'];
    $incoming_date = $_POST['incoming_date'];
    $courier = $_POST['courier_name'];
    $courier_charge = floatval($_POST['courier_charge']);
    $company_name = $_POST['company_name']; // ✅ NEW FIELD

    $items = $_POST['item_name'];
    $particulars = $_POST['particular_name'];
    $specs = $_POST['specification'];
    $models = $_POST['model_number'];
    $qtys = $_POST['qty'];
    $rates = $_POST['rate'];
    $gsts = $_POST['gst'];
    $faults = $_POST['fault_count'];
    $fault_remarks = $_POST['fault_remarks'];

    $count = count($items);
    $errors = [];
    $products_total = 0;

    for ($i = 0; $i < $count; $i++) {
        $qty = floatval($qtys[$i]);
        $rate = floatval($rates[$i]);
        $gst = floatval($gsts[$i]);
        $fault_count = !empty($faults[$i]) ? intval($faults[$i]) : 0;
        $remark = isset($fault_remarks[$i]) ? trim($fault_remarks[$i]) : '';

        if ($qty < 0) $qty = 0;
        if ($rate < 0) $rate = 0;
        if ($fault_count < 0) $fault_count = 0;

        if ($fault_count > $qty) {
            $errors[] = "Row ".($i+1).": Fault count cannot exceed quantity ($qty).";
            $fault_count = $qty;
        }

        if ($fault_count > 0 && empty($remark)) {
            $errors[] = "Row ".($i+1).": Please enter fault remarks for the fault count.";
        }

        $total = ($qty * $rate) + $gst;
        $products_total += $total;

        // ✅ Insert into purchase_stock
        $sql = "INSERT INTO purchase_stock 
                (invoice_number, incoming_date, courier_name, company_name, item_name, particular_name, specification, model_number, qty, rate, gst, total, fault_count) 
                VALUES 
                ('$invoice', '$incoming_date', '$courier', '$company_name', '{$items[$i]}', '{$particulars[$i]}', '{$specs[$i]}', '{$models[$i]}', $qty, $rate, $gst, $total, ".($fault_count ? $fault_count : "NULL").")";

        if ($conn->query($sql)) {
            $purchase_stock_id = $conn->insert_id;  // ✅ capture ID
        } else {
            $errors[] = "Row ".($i+1).": ".$conn->error;
            continue;
        }

        // ✅ Insert into fault_stock if needed
        if ($fault_count > 0) {
            // $username = ucfirst(htmlspecialchars($_SESSION['username'] ?? 'User'));
            $sql_fault = "INSERT INTO fault_stock 
                        (purchase_stock_id, company_name, item_name, particular_name, specification, model_number, qty, remarks, fault_date, given_to, created_at, updated_at)
                        VALUES 
                        ($purchase_stock_id, '$company_name', '{$items[$i]}', '{$particulars[$i]}', '{$specs[$i]}', '{$models[$i]}', $fault_count, '".addslashes($remark)."', '$incoming_date', 'Nilatech', NOW(), NOW())";

            if (!$conn->query($sql_fault)) {
                $errors[] = "Fault Stock Row ".($i+1).": ".$conn->error;
            }
        }
    }

    // ✅ Save company_name in invoice
    $invoice_total = $products_total + $courier_charge;
    $sql_invoice = "INSERT INTO purchase_invoice 
                    (invoice_number, incoming_date, courier_name, company_name, courier_charge, total_amount) 
                    VALUES ('$invoice', '$incoming_date', '$courier', '$company_name', $courier_charge, $invoice_total)";
    if (!$conn->query($sql_invoice)) {
        $errors[] = "Invoice Insert Error: ".$conn->error;
    }

    // ✅ Redirect back
    header("Location: inventory.php");
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Inward Stock</title>
    <link rel="icon" type="image/png" href="assets/logo/logo_icon.png">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <style>
        body { display: flex; flex-direction: column; min-height: 100vh; }
        main { flex: 1; }
        table.table { table-layout: fixed; width: 100%; }
        table.table input { width: 100%; box-sizing: border-box; }
        input::placeholder { font-size: 10px; color: #999; }
        footer { background: #f8f9fa; text-align: center; padding: 10px 0; }
        footer img { height: 20px; vertical-align: middle; }
    </style>
</head>
<body class="bg-light">

<?php include 'navbar.php'; ?>

<main class="container mt-3">
    <h2 class="mb-4 text-center text-success">Inward Stock Entry</h2>

    <?php if($msg != "") { ?>
        <div class="alert alert-info text-center"><?php echo $msg; ?></div>
    <?php } ?>

    <div class="card shadow-sm">
        <div class="card-body">
            <form method="POST">
                <!-- Row 1 -->
                <div class="row g-3 mb-3">
                    <div class="col-md-3">
                        <label class="form-label">Invoice Number</label>
                        <input type="text" class="form-control" name="invoice_number" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Date</label>
                        <input type="date" class="form-control" name="incoming_date" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Courier Name</label>
                        <input type="text" class="form-control" name="courier_name">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Company Name</label>
                        <input type="text" class="form-control" name="company_name" required>
                    </div>
                </div>

                <!-- Row 2 -->
                <div class="row g-3 mb-3">
                    <div class="col-md-4">
                        <label class="form-label">Courier Charge</label>
                        <input type="number" step="0.01" class="form-control" name="courier_charge" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Number of Products</label>
                        <input type="number" class="form-control" id="num_products" min="1" value="1">
                    </div>
                    <div class="col-md-3 align-self-end">
                        <button type="button" class="btn btn-success" onclick="addRows()">Generate Rows</button>
                    </div>
                </div>

                <!-- Product Table -->
                <div class="table-responsive">
                    <table class="table table-bordered bg-white shadow-sm">
                        <thead class="table-dark">
                            <tr>
                                <th>Item Name</th>
                                <th>Particular</th>
                                <th>Specification</th>
                                <th>Model</th>
                                <th>Qty</th>
                                <th>Rate</th>
                                <th>GST %</th>
                                <th>Fault Count</th>
                                <th>Fault Remarks</th>
                            </tr>
                        </thead>
                        <tbody id="product_body"></tbody>
                    </table>
                </div>

                <!-- Submit Button -->
                <div class="text-center mt-3" id="submit_section" style="display:none;">
                    <button type="submit" class="btn btn-success">Submit</button>
                </div>
            </form>
        </div>
    </div>
</main>

<!-- Footer -->
<footer>
    Powered By <img src="assets/logo/logo.png" alt="Logo">
</footer>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function addRows() {
        let num = parseInt(document.getElementById('num_products').value);
        let tbody = document.getElementById('product_body');
        tbody.innerHTML = ""; // clear old rows if any

        for (let i = 0; i < num; i++) {
            let row = document.createElement('tr');
            row.innerHTML = `
                <td><input type="text" class="form-control" name="item_name[]" required></td>
                <td><input type="text" class="form-control" name="particular_name[]"></td>
                <td><input type="text" class="form-control" name="specification[]"></td>
                <td><input type="text" class="form-control" name="model_number[]"></td>
                <td><input type="number" class="form-control qty" name="qty[]" required min="0"></td>
                <td><input type="number" step="0.01" class="form-control" name="rate[]" required min="0"></td>
                <td><input type="number" step="0.01" class="form-control" name="gst[]"></td>
                <td><input type="number" class="form-control fault_count" name="fault_count[]" min="0" placeholder="Optional"></td>
                <td><input type="text" class="form-control fault_remarks" name="fault_remarks[]" placeholder="Required if fault > 0"></td>
            `;
            tbody.appendChild(row);
        }

        document.getElementById("submit_section").style.display = "block";
    }
</script>
</body>
</html>
