<?php
require_once('../include/Session.php');
require_once('../include/Functions.php');
require_once('../include/Crud.php');
require_once("../include/Controller.php");

$Controller = new Controller();

$user_id = $_SESSION['user_id'];

$current_form_number = 3;

$form_check_result = $Controller->fmCheckWh($_SESSION['user_id']);

// Check if $form_check_result is not null and if it has at least one element
if ($form_check_result !== null && isset($form_check_result[0]['form_check'])) {
    $form_check = $form_check_result[0]['form_check'];

    // Cast $form_check to an integer
    $form_check = (int)$form_check;

    // var_dump($form_check); 
    if ($form_check === $current_form_number) {
        header("Location: wh2.php");
        exit();
    }
}


if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (isset($_POST['edu']) && is_array($_POST['edu'])) {
        $eduData = $_POST['edu'];
        try {
            $user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
            $insertedIds = array(); // Initialize an array to store all inserted IDs
            
            foreach ($eduData as $eduItem) {
                if (isset($eduItem['designation'], $eduItem['rank'], $eduItem['job_func'], 
                    $eduItem['supervisor'], $eduItem['skill_set'], $eduItem['wh_hs_from'], $eduItem['wh_hs_to'])) {
                    
                    // Extract data from the current $eduItem
                    $designation = $eduItem['designation'];
                    $rank = $eduItem['rank'];
                    $job_func = $eduItem['job_func'];
                    $supervisor = $eduItem['supervisor'];
                    $skill_set = $eduItem['skill_set'];
                    $wh_hs_from = $eduItem['wh_hs_from'];
                    $wh_hs_to = $eduItem['wh_hs_to'];

                    // Create data array for insertion
                    $data = [
                        "form_check" => 3,
                        "designation" => $designation,
                        "ra_nk" => $rank,
                        "job_func" => $job_func,
                        "supervisor" => $supervisor,
                        "skill_set" => $skill_set,
                        "wh_hs_from" => $wh_hs_from,
                        "wh_hs_to" => $wh_hs_to,
                        "user_id" => $user_id,
                    ];

                    // Insert data into the database
                    $lastInsertedId = $Controller->createWH($data);
                    if ($lastInsertedId) {
                        $insertedIds[] = $lastInsertedId; // Store the inserted ID
                    } else {
                        throw new Exception("Failed to insert data");
                    }
                } else {
                    throw new Exception("Incomplete data");
                }
            }

            // Check if any rows were successfully inserted
            if (!empty($insertedIds)) {
                // Set session variables and redirect
                $_SESSION['wh_id'] = $insertedIds;
                $_SESSION['staff_wh'] = true;
                $_SESSION["successMsg"] = "Successfully registered";
                
                // Redirect after 5 seconds
                echo '<script>
                        setTimeout(function() {
                            window.location.href = "wh2.php"; 
                        }, 1000); 
                      </script>';
                exit();
            } else {
                // No rows were inserted
                $_SESSION['errorMsg'] = "Failed to insert data";
            }
        } catch (PDOException $e) {
            // Handle database errors
            $_SESSION['errorMsg'] = "Database error: " . $e->getMessage();
        } catch (Exception $e) {
            // Handle unexpected exceptions
            $_SESSION['errorMsg'] = "An unexpected error occurred: " . $e->getMessage();
        }
    } else {
        // Handle case where edu array is not set or is not an array
        $_SESSION['errorMsg'] = "Array is not set";
    }
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Healing School | Staff Portal</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta content="" name="description">
    <meta content="" name="author">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <!-- App favicon -->
    <link rel="shortcut icon" href="assets/images/favicon.ico">

    <!-- App css -->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="assets/css/jquery-ui.min.css" rel="stylesheet">
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css">
    <link href="assets/css/metisMenu.min.css" rel="stylesheet" type="text/css">
    <link href="../plugins/daterangepicker/daterangepicker.css" rel="stylesheet" type="text/css">
    <link href="assets/css/app.min.css" rel="stylesheet" type="text/css">

</head>

<body class="dark-sidenav">
    <!-- Left Sidenav -->
    <?php
    include_once("../components/sidenav.php");
    ?>
    <!-- end left-sidenav-->


    <div class="page-wrapper">
        <!-- Top Bar Start -->
        <?php
        include_once("../components/topbar.php");
        ?>

        <!-- Top Bar End -->

        <!-- Page Content-->
        <div class="page-content">
            <div class="container-fluid">
                <!-- Page-Title -->
                <div class="row">
                    <div class="col-sm-12">
                        <div class="page-title-box">
                            <div class="row">
                                <div class="col">
                                    <h4 class="page-title">Staff Portal</h4>
                                    <ol class="breadcrumb">
                                        <li class="breadcrumb-item"><a href="javascript:void(0);">Staff Portal</a></li>
                                        <li class="breadcrumb-item active">Forms</li>
                                    </ol>
                                </div><!--end col-->
                                <div class="col-auto align-self-center">
                                    <a href="#" class="btn btn-sm btn-outline-primary" id="Dash_Date">
                                        <span class="day-name" id="Day_Name">Today:</span>&nbsp;
                                        <span class="" id="Select_date">Jan 11</span>
                                        <i data-feather="calendar" class="align-self-center icon-xs ml-1"></i>
                                    </a>

                                </div><!--end col-->
                            </div><!--end row-->
                        </div><!--end page-title-box-->
                    </div><!--end col-->
                </div><!--end row-->
                <!-- end page title end breadcrumb -->
                <?php
                echo errorMsg();
                echo successMsg();
                echo infoMsg();

                ?>
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Staff Portal</h4>
                                <p class="text-muted mb-0">Please ensure all details are filled out before submitting.
                            </div><!--end card-header-->
                            <div class="card-body">
                                <form method="POST" class="form-horizontal well">
                                    <h3>Work History</h3>

                                    <fieldset>
                                        <div class="repeater-default">
                                            <div data-repeater-list="edu">
                                                <div data-repeater-item="">
                                                    <div class="form-group row d-flex align-items-end">

                                                        <!-- <div class="form-group row d-flex align-items-end"> -->

                                                        <div class="col-sm-4 col-md-6">
                                                            <label class="control-label">Designation</label>
                                                            <input name="edu[0][designation]" type="text" class="form-control" required>
                                                        </div><!--end col-->

                                                        <div class="col-sm-4 col-md-6">
                                                            <label class="control-label">Rank</label>
                                                            <input type="text" name="edu[0][rank]" class="form-control" required>
                                                        </div><!--end col-->
                                                    </div><!--end row-->
                                                    <div class="form-group row d-flex align-items-end">

                                                        <div class="col-sm-4 col-md-6">
                                                            <label class="control-label">Job Function</label>
                                                            <input name="edu[0][job_func]" type="text" class="form-control" required>
                                                        </div><!--end col-->

                                                        <div class="col-sm-4 col-md-6">
                                                            <label class="control-label">Supervisor</label>
                                                            <input type="text" name="edu[0][supervisor]" class="form-control" required>
                                                        </div><!--end col-->
                                                    </div><!--end row-->
                                                    <div class="form-group row d-flex align-items-end">

                                                        <div class="col-sm-4 col-md-6">
                                                            <label class="control-label">Skill Set (What you can do)</label>
                                                            <input name="edu[0][skill_set]" type="text" class="form-control" required>
                                                        </div><!--end col-->

                                                        <div class="col-sm-4 col-md-6">
                                                            <label class="control-label">Work History in Healing School</label>
                                                            <div class="d-flex align-items-center">From
                                                                <input type="date" name="edu[0][wh_hs_from]" class="form-control mr-1" required>
                                                                To
                                                                <input type="date" name="edu[0][wh_hs_to]" class="form-control" required>
                                                            </div>

                                                        </div>
                                                        <!--end col-->
                                                        <!-- </div> -->
                                                        <!--end row-->


                                                        <input id="" value="<?= $_SESSION['user_id'] ?>" name="edu[0][user_id]" type="hidden" class="form-control" />

                                                        <div class="col-sm-1 col-md-2 mt-2">
                                                            <span data-repeater-delete="" class="btn btn-danger btn-sm">
                                                                <span class="far fa-trash-alt mr-1"></span> Delete
                                                            </span>
                                                        </div><!--end col-->
                                                    </div><!--end row-->
                                                </div>
                                                <!--end /div-->


                                            </div><!--end repet-list-->
                                            <div class="form-group mb-0 row">
                                                <div class="col-sm-12">
                                                    <span data-repeater-create="" class="btn btn-secondary btn-sm">
                                                        <span class="fas fa-plus"></span> Add
                                                    </span>
                                                </div><!--end col-->
                                            </div><!--end row-->
                                            <div class="button-items" style="float:right">
                                                <script>
                                                    // Function to store the current page URL in session storage
                                                    function storePreviousPage() {
                                                        sessionStorage.setItem('previousPage', window.location.href);
                                                    }

                                                    // Function to redirect the user to the previous page
                                                    function redirectToPreviousPage() {
                                                        var previousPage = sessionStorage.getItem('previousPage');
                                                        if (previousPage) {
                                                            window.location.href = previousPage;
                                                        } else {
                                                            window.location.href = '../index.php';
                                                        }
                                                    }
                                                </script>

                                                <button type="button" class="btn btn-outline-secondary btn-square btn-skew waves-effect waves-light" onclick="redirectToPreviousPage()">
                                                    <span>Previous</span>
                                                </button>
                                                <button type="submit" class="btn btn-outline-primary btn-square btn-skew waves-effect waves-light" onclick="storePreviousPage(); document.getElementById('form').submit();">
                                                    <span>Next</span>
                                                </button>

                                            </div>
                                        </div> <!--end repeter-->
                                    </fieldset><!--end fieldset-->



                                </form>
                                <!--end form-->
                            </div>
                            <!--end card-body-->
                        </div><!--end card-->
                    </div> <!-- end col -->


                    <!--end col-->
                </div> <!-- end row -->

            </div><!-- container -->

            <?php include_once('../components/footer.php') ?>

        </div>
        <!-- end page content -->
    </div>
    <!-- end page-wrapper -->




    <!-- jQuery  -->
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/metismenu.min.js"></script>
    <script src="assets/js/waves.js"></script>
    <script src="assets/js/feather.min.js"></script>
    <script src="assets/js/simplebar.min.js"></script>
    <script src="assets/js/jquery-ui.min.js"></script>
    <script src="assets/js/moment.js"></script>
    <script src="../plugins/daterangepicker/daterangepicker.js"></script>

    <script src="../plugins/repeater/jquery.repeater.min.js"></script>
    <script src="assets/pages/jquery.form-repeater.js"></script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>

</body>

</html>