<?php
session_start();
$message = "";
$shift_status = "";

$curent_date = (new DateTime())->format('Y-m-d H:i:s');  
if (isset($_POST['clock_in'])) {
    $clock_no = $_POST['clock_no'];
    $sql = "SELECT * FROM admin WHERE clock_no = '$clock_no' AND id='".$_SESSION['user_id']."'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        $user_id = $user['id'];

        $sql = "SELECT * FROM shifts WHERE user_id = $user_id AND status = 'active'";
        $result = $conn->query($sql);

       if ($result->num_rows == 0) {
			$start_time = (new DateTime())->format('Y-m-d H:i:s'); 
			$sql = "INSERT INTO shifts (user_id, start_time, status) VALUES ($user_id, '$start_time', 'active')";

			if ($conn->query($sql) === TRUE) {
				$message = "Shift has started.";
				$shift_status = "active";
			}
		} else {
			$message = "You are already on a shift.";
			$shift_status = "active";
		}

    } else {
        $message = "Incorrect Clock Code.";
    }
}

if (isset($_POST['pause_resume'])) {
    $clock_no = $_POST['clock_no'];
    $sql = "SELECT * FROM admin WHERE clock_no = '$clock_no'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        $user_id = $user['id'];

        $sql = "SELECT * FROM shifts WHERE user_id = $user_id AND status = 'active'";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            $shift = $result->fetch_assoc();
            $shift_id = $shift['id'];

            $sql = "SELECT * FROM transactions WHERE shift_id = $shift_id AND status = 'active' AND pause_end IS NULL";
            $result = $conn->query($sql);

            if ($result->num_rows == 0) {
                $sql = "INSERT INTO transactions (shift_id, pause_start, status) VALUES ($shift_id, '$curent_date', 'active')";
                if ($conn->query($sql) === TRUE) {
                    $message = "Shift has been paused.";
                    $shift_status = "paused";
                }
            } else {
                $transaction = $result->fetch_assoc();
                $transaction_id = $transaction['id'];

                $sql = "UPDATE transactions SET pause_end = '$curent_date', status = 'inactive' WHERE id = $transaction_id";
                if ($conn->query($sql) === TRUE) {
                    $message = "Shift has been resumed.";
                    $shift_status = "active";
                }
            }
        } else {
            $message = "No active shift found.";
        }
    } else {
        $message = "Incorrect Clock Code.";
    }
}

if (isset($_POST['end_shift'])) {
    $clock_no = $_POST['clock_no'];
    $sql = "SELECT * FROM admin WHERE clock_no = '$clock_no'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        $user_id = $user['id'];

        // Find the active shift
        $sql = "SELECT * FROM shifts WHERE user_id = $user_id AND status = 'active'";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            $shift = $result->fetch_assoc();
            $shift_id = $shift['id'];

            $sql = "UPDATE transactions SET pause_end = '$curent_date', status = 'inactive' WHERE shift_id = $shift_id AND status = 'active'";
            $conn->query($sql);

            // End the shift
            $sql = "UPDATE shifts SET end_time = '$curent_date', status = 'inactive' WHERE id = $shift_id";
            if ($conn->query($sql) === TRUE) {
                $start_time = strtotime($shift['start_time']);
                $end_time = strtotime(date('Y-m-d H:i:s'));
				/* 
                $start_time = strtotime('2024-12-01 06:58:55.000000');
                $end_time = strtotime(date('2024-12-01 07:58:55.000000')); */
                $total_hours = ($end_time - $start_time) / 3600;

                $sql = "SELECT SUM(TIMESTAMPDIFF(MINUTE, pause_start, pause_end)) AS paused_minutes FROM transactions WHERE shift_id = $shift_id AND pause_end IS NOT NULL";
                $result = $conn->query($sql);
                $paused_minutes = $result->fetch_assoc()['paused_minutes'] ?? 0;
                $paused_hours = $paused_minutes / 60;
                $worked_hours = $total_hours - $paused_hours;

                $day_of_week = date('N', $start_time); // 1 = Monday, 7 = Sunday
                $pay_amount = calculatePay($worked_hours, $day_of_week);

                $sql = "UPDATE shifts SET total_hours = $worked_hours, pay_amount = $pay_amount WHERE id = $shift_id";
                $conn->query($sql);

                $message = "Shift has ended. Total Pay: ₹$pay_amount";
                $shift_status = "ended";
            }
        } else {
            $message = "No active shift found.";
        }
    } else {
        $message = "Incorrect Clock Code.";
    }
}

function calculatePay($worked_hours, $day_of_week) {
    $standard_rate = 100; 
    if ($day_of_week >= 1 && $day_of_week <= 4) {
        if ($worked_hours <= 9.75) {
            return $worked_hours * $standard_rate;
        } else {
            return (9.75 * $standard_rate) + (($worked_hours - 9.75) * $standard_rate * 1.33);
        }
    } elseif ($day_of_week == 5 || $day_of_week == 6) {
        return $worked_hours * $standard_rate * 1.5;
    } elseif ($day_of_week == 7) {
        return $worked_hours * $standard_rate * 2;
    }
    return 0;
}
?>

<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-12">
                <h1 class="m-0 text-primary"><?=$page_header;?></h1>
            </div>
        </div>
        <!-- /.row -->
    </div>
    <!-- /.container-fluid -->
</div>
<section class="content">
	<div class="container-fluid">
		<div class="row">
			<div class="col-lg-3"></div>
			<div class="col-lg-6">
				
  <style>
    
    .form-container {
      background-color: #fff;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* Shadow effect */
      width: 100%;
      max-width: 600px;
      text-align: center;
    }
    h2 {
      color: #4A4A8D;
      margin-bottom: 20px;
    }
    input[type="text"] {
      width: calc(100% - 22px);
      padding: 10px;
      font-size: 16px;
      border: 1px solid #ccc;
      border-radius: 5px;
      margin-bottom: 20px;
    }
    button {
      width: 100%;
      padding: 12px;
      font-size: 16px;
      margin: 5px 0;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }
    button[name="clock_in"] {
      background-color: #4A4A8D;
      color: #fff;
    }
    button[name="pause_resume"] {
      background-color: #FFA500;
      color: #fff;
    }
    button[name="end_shift"] {
      background-color: #D9534F;
      color: #fff;
    }
    button:hover {
      opacity: 0.9;
    }
    .print {
      margin-top: 20px;
      color: #333;
      font-weight: bold;
    }
	h2 {
        font-family: 'Poppins', sans-serif;
        color: #4A4A8D;
        margin-bottom: 20px;
        font-size: 34px;
        font-weight: 500; /* Medium weight for a stylish look */
        text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2); /* Optional shadow for a 3D effect */
    }
  </style>
 
  <div class="form-container">
    <h2>Clock In/Out System</h2>
    <form method="POST" action="">
        <input type="text" name="clock_no" placeholder="Enter Clock Code" required>
        
        <?php if ($shift_status != "active" && $shift_status != "paused"): ?>
            <button type="submit" name="clock_in" id="clock_in_btn">Clock In</button>
        <?php endif; ?>

        <?php if ($shift_status == "active"): ?>
            <button type="submit" name="pause_resume" id="pause_resume_btn">Pause Shift</button>
        <?php endif; ?>
        <?php if ($shift_status == "paused"): ?>
            <button type="submit" name="pause_resume" id="pause_resume_btn">Resume Shift</button>
        <?php endif; ?>

        <?php if ($shift_status == "active" || $shift_status == "paused"): ?>
            <button type="submit" name="end_shift" id="end_shift_btn">End Shift</button>
        <?php endif; ?>
    </form>
    <p class="print hide"><?php echo $message; ?></p>
</div>

</div>

		</div>
	</div>
</section>