<?php    
error_reporting(E_ALL);    
ini_set('display_errors', 1);    
    
ob_start(); // Start output buffering    
    
require_once('includes/load.php'); // Load database connection and functions    

// Function to format hours for display
function format_hours($decimal_hours) {
    $hours = floor($decimal_hours);
    $minutes = round(($decimal_hours - $hours) * 60);
    return sprintf("%d jam %02d menit", $hours, $minutes);
}
    
// Function to create a new overtime record    
function create_overtime_record($employee_name, $overtime_date, $start_time, $end_time, $reason) {    
    global $db;    
    
    // Fetch employee ID based on the name    
    $employee_name = $db->escape($employee_name);    
    $sql = "SELECT id FROM employees WHERE name = '{$employee_name}' LIMIT 1";    
    $result = $db->query($sql);    
    $employee = $db->fetch_assoc($result);    
    
    if ($employee) {    
        $employee_id = $employee['id'];    
        $overtime_date = $db->escape($overtime_date);    
        $start_time = $db->escape($start_time);    
        $end_time = $db->escape($end_time);    
            
        // Calculate hours worked (handle overnight overtime)
        $start_datetime = new DateTime($overtime_date . ' ' . $start_time);
        $end_datetime = new DateTime($overtime_date . ' ' . $end_time);
        
        // If end time is earlier than start time, it means it's the next day
        if ($end_datetime < $start_datetime) {
            $end_datetime->modify('+1 day');
        }
        
        $interval = $start_datetime->diff($end_datetime);
        $hours_worked = $interval->h + ($interval->i / 60); // Convert to decimal hours

        $reason = $db->escape($reason);    
    
        $sql = "INSERT INTO overtime_attendance (employee_id, overtime_date, start_time, end_time, hours_worked, reason)    
                VALUES ('{$employee_id}', '{$overtime_date}', '{$start_time}', '{$end_time}', {$hours_worked}, '{$reason}')";    
        return $db->query($sql);    
    } else {    
        return false; // Employee not found    
    }    
}    
    
// Function to delete an overtime record    
function delete_overtime_record($id) {    
    global $db;    
    
    $id = intval($id);    
    $sql = "DELETE FROM overtime_attendance WHERE id = {$id}";    
    
    return $db->query($sql);    
}    
    
// Process form submission for adding a new overtime record    
if (isset($_POST['submit_overtime'])) {    
    $employee_name = $_POST['employee_name'];    
    $overtime_date = $_POST['overtime_date'];    
    $start_time = $_POST['start_time'];    
    $end_time = $_POST['end_time'];    
    $reason = $_POST['reason'];    
    
    if (create_overtime_record($employee_name, $overtime_date, $start_time, $end_time, $reason)) {    
        $msg = "Overtime record created successfully.";    
    } else {    
        $msg = "Failed to create overtime record. Employee not found.";    
    }    
    header('Location: overtime_absensi.php');    
    exit();    
}    
    
// Process deletion of an overtime record    
if (isset($_GET['delete'])) {    
    $id = $_GET['delete'];    
    if (delete_overtime_record($id)) {    
        $msg = "Overtime record deleted successfully.";    
    } else {    
        $msg = "Failed to delete overtime record.";    
    }    
    header('Location: overtime_absensi.php');    
    exit();    
}    
    
// Fetch existing overtime records with optional search    
$search_query = '';    
if (isset($_POST['search'])) {    
    $search_query = $db->escape($_POST['search_query']);    
}    
    
// Updated SQL query to include division    
$sql = "SELECT oa.*, e.name as employee_name, e.division as employee_division FROM overtime_attendance oa    
        JOIN employees e ON oa.employee_id = e.id    
        WHERE e.name LIKE '%{$search_query}%' OR oa.overtime_date LIKE '%{$search_query}%'    
        ORDER BY oa.overtime_date DESC";    
$records = $db->query($sql);    
    
// Fetch employee names for autocomplete    
$employee_names = [];    
$sql = "SELECT name, division FROM employees";    
$result = $db->query($sql);    
while ($row = $db->fetch_assoc($result)) {    
    $employee_names[] = ['name' => $row['name'], 'division' => $row['division']];    
}    
  
// Simple header    
?>    
<!DOCTYPE html>    
<html lang="en">    
<head>    
    <meta charset="UTF-8">    
    <meta name="viewport" content="width=device-width, initial-scale=1.0">    
    <title>Overtime Attendance - HRIS</title>    
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">    
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">    
    <style>    
        body {    
            background-color: #f4f7fa;    
        }    
        .card-header {    
            background-color: #007bff;    
            color: white;    
        }    
        .table th, .table td {    
            vertical-align: middle;    
        }    
        .form-control:focus {    
            border-color: #007bff;    
            box-shadow: 0 0 5px rgba(0, 123, 255, .5);    
        }    
        .btn-primary {    
            background-color: #007bff;    
            border-color: #007bff;    
        }    
        .btn-primary:hover {    
            background-color: #0056b3;    
            border-color: #0056b3;    
        }    
        .alert {    
            margin-top: 20px;    
        }    
    </style>    
</head>    
<body>    
    
<div class="container-fluid mt-5">  <!-- Changed to container-fluid -->  
    <h2 class="text-center mb-4">Overtime Attendance Management</h2>    
    <?php if (isset($msg)): ?>    
        <div class="alert alert-info"><?php echo $msg; ?></div>    
    <?php endif; ?>    
  
    <!-- Back Button -->  
    <div class="text-right mb-3">  
        <a href="human_resource.php" class="btn btn-secondary">Back</a>  
    </div>  
    
    <div class="card mb-4">    
        <div class="card-header">    
            <h4 class="card-title">Add Overtime Record</h4>    
        </div>    
        <div class="card-body">    
            <form action="overtime_absensi.php" method="post">    
                <div class="form-row">    
                    <div class="form-group col-md-6">    
                        <label for="employee_name">Employee Name:</label>    
                        <input type="text" name="employee_name" id="employee_name" class="form-control" required>    
                    </div>    
                    <div class="form-group col-md-6">    
                        <label for="division">Division:</label>    
                        <input type="text" name="division" id="division" class="form-control" readonly required>    
                    </div>    
                </div>    
                <div class="form-row">    
                    <div class="form-group col-md-6">    
                        <label for="overtime_date">Overtime Date:</label>    
                        <input type="date" name="overtime_date" id="overtime_date" class="form-control" required>    
                    </div>    
                </div>    
                <div class="form-row">    
                    <div class="form-group col-md-6">    
                        <label for="start_time">Start Time (HH:MM):</label>    
                        <input type="text" name="start_time" id="start_time" class="form-control" placeholder="HH:MM" required pattern="([01]?[0-9]|2[0-3]):[0-5][0-9]">    
                    </div>    
                    <div class="form-group col-md-6">    
                        <label for="end_time">End Time (HH:MM):</label>    
                        <input type="text" name="end_time" id="end_time" class="form-control" placeholder="HH:MM" required pattern="([01]?[0-9]|2[0-3]):[0-5][0-9]">    
                    </div>    
                </div>    
                <div class="form-row">    
                    <div class="form-group col-md-12">    
                        <label for="reason">Reason:</label>    
                        <input type="text" name="reason" id="reason" class="form-control">    
                    </div>    
                </div>    
                <button type="submit" name="submit_overtime" class="btn btn-primary">Add Overtime Record</button>    
            </form>    
        </div>    
    </div>    
    
    <div class="card mb-4">    
        <div class="card-header">    
            <h4 class="card-title">Search Overtime Records</h4>    
        </div>    
        <div class="card-body">    
            <form action="overtime_absensi.php" method="post">    
                <div class="form-row">    
                    <div class="form-group col-md-8">    
                        <input type="text" name="search_query" class="form-control" placeholder="Search by employee name or date..." value="<?php echo htmlspecialchars($search_query); ?>">    
                    </div>    
                    <div class="form-group col-md-4">    
                        <button type="submit" name="search" class="btn btn-primary">Search</button>    
                    </div>    
                </div>    
            </form>    
        </div>    
    </div>    
    
    <div class="card">    
        <div class="card-header">    
            <h4 class="card-title">Existing Overtime Records</h4>    
        </div>    
        <div class="card-body">    
            <div class="table-responsive">  <!-- Added table-responsive for better layout -->  
                <table class="table table-bordered">    
                    <thead class="thead-dark">    
                        <tr>    
                            <th>ID</th>    
                            <th>Employee Name</th>    
                            <th>Division</th>    
                            <th>Overtime Date</th>    
                            <th>Start Time</th>    
                            <th>End Time</th>    
                            <th>Hours Worked</th>    
                            <th>Reason</th>    
                            <th>Action</th>    
                        </tr>    
                    </thead>    
                    <tbody>    
                        <?php if ($records && $db->num_rows($records) > 0): ?>    
                            <?php while ($row = $db->fetch_assoc($records)): ?>    
                                <tr>    
                                    <td><?php echo $row['id']; ?></td>    
                                    <td><?php echo htmlspecialchars($row['employee_name']); ?></td>    
                                    <td><?php echo htmlspecialchars($row['employee_division']); ?></td>    
                                    <td><?php echo htmlspecialchars($row['overtime_date']); ?></td>    
                                    <td><?php echo htmlspecialchars($row['start_time']); ?></td>    
                                    <td><?php echo htmlspecialchars($row['end_time']); ?></td>    
                                    <td><?php echo format_hours($row['hours_worked']); ?></td>    
                                    <td><?php echo htmlspecialchars($row['reason']); ?></td>    
                                    <td>    
                                        <a href="edit_overtime.php?id=<?php echo $row['id']; ?>" class="btn btn-warning">    
                                            <i class="fas fa-edit"></i> Edit    
                                        </a>    
                                        <a href="overtime_absensi.php?delete=<?php echo $row['id']; ?>" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this record?');">    
                                            <i class="fas fa-trash"></i> Delete    
                                        </a>    
                                    </td>    
                                </tr>    
                            <?php endwhile; ?>    
                        <?php else: ?>    
                            <tr>    
                                <td colspan="9" class="text-center">No overtime records found.</td>    
                            </tr>    
                        <?php endif; ?>    
                    </tbody>    
                </table>    
            </div>    
        </div>    
    </div>    
</div>    
    
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>    
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>    
<script>    
    $(function() {    
        var employeeData = <?php echo json_encode($employee_names); ?>; // Pass PHP array to JavaScript    
        $("#employee_name").autocomplete({    
            source: employeeData.map(function(emp) { return emp.name; }),    
            minLength: 2, // Start searching after typing 2 characters    
            select: function(event, ui) {    
                // Find the selected employee's division    
                var selectedEmployee = employeeData.find(emp => emp.name === ui.item.value);    
                if (selectedEmployee) {    
                    $("#division").val(selectedEmployee.division); // Set the division field    
                }    
            }    
        });    
    });    
</script>    
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>    
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>    
</body>    
</html>    