<?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 = 2;


// Get the form check result from the database for the current user
$form_check_result = $Controller->fmCheckEd($_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) {
        // Redirect to 'wh.php' if the form check result matches the current form number
        header("Location: wh.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;

            foreach ($eduData as $eduItem) {
                if (isset($eduItem['edu_qua'], $eduItem['year_of_grad'])) {
                    $edu_qua = $eduItem['edu_qua'];
                    $year_of_grad = $eduItem['year_of_grad'];

                    // Create data array for insertion
                    $data = [
                        "form_check" => 2,
                        "edu_qua" => $edu_qua,
                        "year_of_grad" => $year_of_grad,
                        "user_id" => $user_id,
                    ];

                    // Insert data into the database
                    $lastInsertedId = $Controller->createEdu($data);

                    // Handle insertion result if needed
                } else {
                    throw new Exception("Incomplete data for education item");
                }
            }

            $_SESSION["successMsg"] = "Successfully registered";
            $_SESSION['ed_id'] = $lastInsertedId;
            $_SESSION['staff_ed'] = true;
            echo '<script>
            setTimeout(function() {
                window.location.href = "wh.php"; 
            }, 1000); 
            </script>';
            exit(); 
        } 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'] = "edu array is not set or is not an array";
    }
}



?>
<!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="Premium Multipurpose Admin & Dashboard Template" 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>Education</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="col-sm-4 col-md-5">
                                                            <label class="control-label">Educational Qualification</label>
                                                            <input name="edu[0][edu_qua]" type="text" class="form-control" required>
                                                        </div><!--end col-->

                                                        <div class="col-sm-4 col-md-5">
                                                            <label class="control-label">Year of Graduation</label>
                                                            <input type="date" name="edu[0][year_of_grad]" class="form-control" required>
                                                        </div><!--end col-->


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

                                                        <div class="col-sm-1 col-md-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>