<?php
/**
 * API untuk mengelola data kehadiran
 * Endpoint: /api/attendance.php
 */

require_once '../config/database.php';

// Set CORS headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    jsonResponse(['error' => 'Database connection failed'], 500);
}

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

try {
    switch ($method) {
        case 'GET':
            handleGetAttendance($db);
            break;
        case 'POST':
            handleUpdateAttendance($db, $input);
            break;
        default:
            jsonResponse(['error' => 'Method not allowed'], 405);
    }
} catch (Exception $e) {
    jsonResponse(['error' => $e->getMessage()], 500);
}

/**
 * GET - Ambil data kehadiran untuk hari ini
 */
function handleGetAttendance($db) {
    $date = $_GET['date'] ?? date('Y-m-d');
    
    $query = "
        SELECT 
            p.id as position_id,
            p.name,
            p.order_index,
            COALESCE(a.status, 'absent') as status,
            a.updated_at
        FROM positions p
        LEFT JOIN attendance a ON p.id = a.position_id AND a.attendance_date = :date
        ORDER BY p.order_index ASC
    ";
    
    $stmt = $db->prepare($query);
    $stmt->bindParam(':date', $date);
    $stmt->execute();
    
    $attendance = $stmt->fetchAll();
    
    jsonResponse([
        'success' => true,
        'date' => $date,
        'data' => $attendance
    ]);
}

/**
 * POST - Update status kehadiran
 */
function handleUpdateAttendance($db, $input) {
    // Validasi input
    $errors = validateInput($input, ['position_id', 'status', 'user_id']);
    if (!empty($errors)) {
        jsonResponse(['error' => 'Validation failed', 'details' => $errors], 400);
    }
    
    $position_id = (int)$input['position_id'];
    $status = $input['status'];
    $user_id = (int)$input['user_id'];
    $date = $input['date'] ?? date('Y-m-d');
    
    // Validasi status
    if (!in_array($status, ['present', 'absent', 'cuti', 'tugas_luar'])) {
        jsonResponse(['error' => 'Invalid status. Must be present, absent, cuti, or tugas_luar'], 400);
    }
    
    // Cek apakah user memiliki akses untuk mengubah status ini
    $userQuery = "SELECT position_id, is_admin FROM users WHERE id = :user_id";
    $userStmt = $db->prepare($userQuery);
    $userStmt->bindParam(':user_id', $user_id);
    $userStmt->execute();
    $user = $userStmt->fetch();
    
    if (!$user) {
        jsonResponse(['error' => 'User not found'], 404);
    }
    
    // Admin bisa mengubah semua, user biasa hanya bisa mengubah posisi sendiri
    if (!$user['is_admin'] && $user['position_id'] != $position_id) {
        jsonResponse(['error' => 'Access denied. You can only update your own attendance'], 403);
    }
    
    // Update atau insert attendance
    $query = "
        INSERT INTO attendance (position_id, attendance_date, status, updated_by)
        VALUES (:position_id, :date, :status, :user_id)
        ON DUPLICATE KEY UPDATE
        status = :status,
        updated_by = :user_id,
        updated_at = CURRENT_TIMESTAMP
    ";
    
    $stmt = $db->prepare($query);
    $stmt->bindParam(':position_id', $position_id);
    $stmt->bindParam(':date', $date);
    $stmt->bindParam(':status', $status);
    $stmt->bindParam(':user_id', $user_id);
    
    if ($stmt->execute()) {
        jsonResponse([
            'success' => true,
            'message' => 'Attendance updated successfully',
            'data' => [
                'position_id' => $position_id,
                'status' => $status,
                'date' => $date
            ]
        ]);
    } else {
        jsonResponse(['error' => 'Failed to update attendance'], 500);
    }
}
?>
