<link rel="stylesheet" href="../css/sweet-alert.css" />
<?php
include("../connection.php");
include("../user.php");

$cur_date = date('Y-m-d H:i:s');
$sys_date = date('Y-m-d');
$user = $_SESSION['user'];

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

    $so_date = $_POST['so_date'];
    
    $branch = $_POST['branch'];
    $store = $_POST['store'];
    $ticket_no = $_POST['ticket_no'];
    $technician = $_POST['technician'];
    $approved_by = $_POST['approved_by'];
    $purpose = $_POST['purpose'];

    // Arrays
    $dptmnt = $_POST['department'];
    $material_name = $_POST['material_name'];
    $qty = $_POST['qty'];
    $mr_no = $_POST['mr_no'];
    $amount = $_POST['amount'];
    $qum = $_POST['qum'];
    $rate_val = $_POST['rate'];
    $success = false;

    for ($i = 1; $i < count($material_name); $i++) {
        $mat_name = $material_name[$i];
        $department = $dptmnt[$i];
        $qty_val = $qty[$i];
        // $val = $value[$i];
        $total_amount = $amount[$i];
        $unit = $qum[$i];
        $rate = $rate_val[$i];

        $insert = $con->query("INSERT INTO outward_master(
            so_date, ticket_no, department, branch, division, material_name, mr_no, qty, value, qum, 
            technician, purpose, approved_by, total_amount, status, created_on, created_by) 
            VALUES (
            '$so_date', '$ticket_no', '$department', '$branch', '$store', '$mat_name', '$mr_no', '$qty_val', '$rate', '$unit', 
            '$technician', '$purpose', '$approved_by', '$total_amount', 0, now(), '$user')");

        if ($insert) {
            $success = true;
        }
        if (!$insert) {
            error_log("Insert failed at row $i: " . $con->error);
        }

    }
}
?>

<?php if (isset($success) && $success): ?>
    <script>
        setTimeout(function () {
            swal({
                title: "Successfully",
                text: "completed!",
                type: "success"
            }, function () {
                window.location = "outward_master.php";
            });
        }, 100);
    </script>
<?php else: ?>
    <script>
        setTimeout(function () {
            swal({
                title: "Not",
                text: "completed!",
                type: "error"
            }, function () {
                window.location = "outward_master.php";
            });
        }, 100);
    </script>
<?php endif; ?>

<script src="../js/sweet-alert.js"></script>