<?php
include "../../connection.php";

if (isset($_POST['deleting_department'])) {
    
    $id = $_POST['department_id'];
    $query = "DELETE FROM tbl_department WHERE department_id = '$id'";
    $query_result = $conn->query($query);
}

// CREATE
if (isset($_POST['adding_department'])) {
    $name = strtoupper($_POST['department_name']);
    $desc = strtoupper($_POST['description']);

    $stmt = $conn->prepare("INSERT INTO tbl_department (department_name, description, date_created) VALUES (?, ?, NOW())");
    $stmt->bind_param("ss", $name, $desc);
    $stmt->execute();
    echo "success";
    exit;
}

// READ
if (isset($_POST['loading_departments'])) {
    echo 
    '
     <table id="mytable" class="table table-striped tbn-sm">
        <thead>
            <tr>
                <th>ID</th>
                <th>DEPARTMENT NAME</th>
                <th>DESCRIPTION</th>
                <th>DATE</th>
                <th>ACTION</th>
            </tr>
        </thead>
        <tbody >
    ';
    $sql = "SELECT * FROM tbl_department ORDER BY department_id DESC";
    $result = $conn->query($sql);

    while ($row = $result->fetch_assoc()) {
        $date = date("F-d-Y", strtotime($row['date_created']));
       echo '
        <tr>
            <td>'.$row['department_id'].'</td>
            <td>'.$row['department_name'].'</td>
            <td>'.$row['description'].'</td>
            <td>'.$date.'</td>
            <td>
                <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#update-department" 
                onclick="edit_deparment(\''.$row['department_id'].'\', \''.$row['department_name'].'\', \''.$row['description'].'\')"
                >
                <i class="fa fa-edit"></i></button>
                <button class="btn btn-sm btn-danger deleteBtn" onclick="delete_department(\''.$row['department_id'].'\')"><i class="fa fa-trash"></i></button>
            </td>
        </tr>
        ';
    }

    echo 
    '
     </tbody>
    </table>
    ';

}

// // READ SINGLE
// if (isset($_POST['action']) && $_POST['action'] == 'get') {
//     $id = $_POST['id'];
//     $result = $conn->query("SELECT * FROM tbl_department WHERE department_id='$id'");
//     echo json_encode($result->fetch_assoc());
//     exit;
// }

// // UPDATE
if (isset($_POST['updating_department'])) {
    $id   = $_POST['d_id'];
    $name = strtoupper($_POST['u_department_name']);
    $desc = strtoupper($_POST['u_description']);

    $stmt = $conn->prepare("UPDATE tbl_department SET department_name = ?, description= ? WHERE department_id = ? ");
    $stmt->bind_param("ssi", $name, $desc, $id);
    $stmt->execute();
    echo "success";
    exit;
}

// // DELETE
// if (isset($_POST['action']) && $_POST['action'] == 'delete') {
//     $id = $_POST['id'];
//     $conn->query("DELETE FROM tbl_department WHERE department_id='$id'");
//     echo "success";
//     exit;
// }
?>
