<?php
session_start();
if (!isset($_SESSION['loggedin'])) {
    exit("unauthorized");
}

include "../database.php";

$user_id = $_POST["user_id"];
$stamp_type_entry = $_POST["stamp_type_entry"];
$stamp_type_exit = $_POST["stamp_type_exit"];
$stamp_transfert = $_POST["stamp_transfert"];
$stamp_transfer_location = $_POST["stamp_transfer_location"];
$stamp_date = $_POST["stamp_date"];
$stamp_time = $_POST["stamp_time"];
$stamp_note = $_POST["stamp_note"];

if ($stamp_type_entry == "true") {
    $stamp_type = 'Entrata';
}
if ($stamp_type_exit == "true") {
    $stamp_type = 'Uscita';
}

if ($stamp_transfert == "true") {
    $in_transfer = 1;
    $transfer_location = $stamp_transfer_location;
} else {
    $in_transfer = 0;
    $transfer_location = "";
}

$datetime    = date("Y-m-d H:i:s");
$stamp_datetime = $stamp_date . "T" . $stamp_time;
$secure               = rand(100000, 1000000);

$sql_attendance    = "SELECT * FROM attendance WHERE month = " . date("m", strtotime($stamp_date)) . " AND year = " . date("Y", strtotime($stamp_date)) . " AND closed = 1";
$result_attendance = mysqli_query($con, $sql_attendance);
if ($result_attendance->num_rows > 0) {
    echo "attendancePresent";
    exit;
}

$sql = "SELECT COUNT(id) AS tot FROM stamps WHERE user_id = $user_id AND date = '$stamp_date' AND type ='$stamp_type'";
$result = mysqli_query($con, $sql);
$stamps = mysqli_fetch_assoc($result);
if ($stamps["tot"] == 4) {
    echo "maxStamps";
} else {
    $sql_insert = "INSERT INTO stamps VALUES (NULL,$user_id,'$stamp_type','$stamp_date','$stamp_time','$stamp_note','$datetime', $in_transfer, 0, '$transfer_location',0,0,'$secure','')";
    if ($con->query($sql_insert) === true) {

        $sql_attendance    = "SELECT * FROM attendance WHERE month = " . date("m", strtotime($stamp_date)) . " AND year = " . date("Y", strtotime($stamp_date)) . "";
        $result_attendance = mysqli_query($con, $sql_attendance);
        if ($result_attendance->num_rows > 0) {
            $attendance        = mysqli_fetch_assoc($result_attendance);

            $sql_update = "UPDATE attendance SET status = 'Da ricalcolare' WHERE id = " . $attendance["id"] . "";
            $con->query($sql_update);
        }

        echo "OK";
    } else {
        echo "error";
    }
}
$con->close();
