<?php
require_once 'config/database.php';
require_once 'utils/helpers.php';

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
        Helpers::sendResponse(false, 'Method not allowed', null, 405);
    }

    // Get and verify token
    $token = Helpers::getBearerToken();
    $userData = Helpers::verifyJWT($token);

    if (!$userData) {
        Helpers::sendResponse(false, 'Unauthorized', null, 401);
    }

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

    // Get user role and permissions
    $query = "SELECT ur.role_level, ur.can_view_department_attendance, u.department_id
              FROM `users` u
              JOIN `user_roles` ur ON u.`role_id` = ur.`id`
              WHERE u.`id` = :user_id";

    $stmt = $db->prepare($query);
    $stmt->bindParam(':user_id', $userData['user_id']);
    $stmt->execute();
    $userPermissions = $stmt->fetch(PDO::FETCH_ASSOC);

    // Get query parameters
    $serviceTemplateId = isset($_GET['service_template_id']) ? $_GET['service_template_id'] : null;
    $serviceOccurrenceId = isset($_GET['service_occurrence_id']) ? $_GET['service_occurrence_id'] : null;
    $startDate = isset($_GET['start_date']) ? $_GET['start_date'] : null;
    $endDate = isset($_GET['end_date']) ? $_GET['end_date'] : null;
    $isValid = isset($_GET['is_valid']) ? $_GET['is_valid'] : null;
    $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 20;
    $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;

    $whereConditions = [];
    $params = [];

    // Determine viewing scope based on role
    if ($userPermissions['role_level'] >= 4) {
        // Admin/Superadmin - can view all
        $viewingScope = 'all';
    } elseif ($userPermissions['can_view_department_attendance'] && $userPermissions['department_id']) {
        // HOD - can view department
        $whereConditions[] = "u.department_id = :department_id";
        $params[':department_id'] = $userPermissions['department_id'];
        $viewingScope = 'department';
    } else {
        // Regular user - only own records
        $whereConditions[] = "a.user_id = :user_id";
        $params[':user_id'] = $userData['user_id'];
        $viewingScope = 'own';
    }

    if ($serviceTemplateId) {
        $whereConditions[] = "st.id = :service_template_id";
        $params[':service_template_id'] = $serviceTemplateId;
    }

    if ($serviceOccurrenceId) {
        $whereConditions[] = "a.service_occurrence_id = :service_occurrence_id";
        $params[':service_occurrence_id'] = $serviceOccurrenceId;
    }

    if ($startDate) {
        $whereConditions[] = "DATE(a.clock_in_time) >= :start_date";
        $params[':start_date'] = $startDate;
    }

    if ($endDate) {
        $whereConditions[] = "DATE(a.clock_in_time) <= :end_date";
        $params[':end_date'] = $endDate;
    }

    if ($isValid !== null) {
        $whereConditions[] = "a.is_valid = :is_valid";
        $params[':is_valid'] = $isValid === 'true' || $isValid === '1' ? 1 : 0;
    }

    $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';

    // Get total count
    $countQuery = "SELECT COUNT(*) as total 
                   FROM `attendance` a
                   JOIN `service_occurrences` so ON a.`service_occurrence_id` = so.`id`
                   JOIN `service_templates` st ON so.`service_template_id` = st.`id`
                   JOIN `users` u ON a.`user_id` = u.`id`
                   $whereClause";

    $stmt = $db->prepare($countQuery);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    $stmt->execute();
    $totalRecords = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

    // Get attendance history
    $query = "SELECT a.id, a.user_id, a.service_occurrence_id, a.clock_in_time, a.clock_out_time, 
                     a.time_spent, a.is_valid, a.notes,
                     st.id as service_template_id, st.name as service_name, st.location,
                     so.occurrence_date, so.start_time, so.end_time,
                     stype.name as service_type,
                     u.first_name, u.last_name, u.email,
                     d.name as department_name,
                     CASE 
                         WHEN a.clock_out_time IS NULL THEN 'in_progress'
                         WHEN a.is_valid = TRUE THEN 'completed'
                         ELSE 'invalid'
                     END as status,
                     CASE 
                         WHEN a.time_spent IS NOT NULL THEN 
                             CONCAT(FLOOR(a.time_spent / 60), 'h ', MOD(a.time_spent, 60), 'm')
                         ELSE NULL
                     END as time_spent_formatted
              FROM `attendance` a
              JOIN `service_occurrences` so ON a.`service_occurrence_id` = so.`id`
              JOIN `service_templates` st ON so.`service_template_id` = st.`id`
              LEFT JOIN `service_types` stype ON st.`service_type_id` = stype.`id`
              JOIN `users` u ON a.`user_id` = u.`id`
              LEFT JOIN `departments` d ON u.`department_id` = d.`id`
              $whereClause
              ORDER BY a.clock_in_time DESC 
              LIMIT :limit OFFSET :offset";

    $stmt = $db->prepare($query);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();

    $history = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Format the history records
    foreach ($history as &$record) {
        $record['user_name'] = trim($record['first_name'] . ' ' . $record['last_name']);
        unset($record['first_name'], $record['last_name']);
    }

    // Get statistics
    $statsQuery = "SELECT 
                       COUNT(*) as total_records,
                       COUNT(CASE WHEN a.is_valid = TRUE THEN 1 END) as valid_attendances,
                       COUNT(CASE WHEN a.is_valid = FALSE THEN 1 END) as invalid_attendances,
                       AVG(a.time_spent) as average_time_spent
                   FROM `attendance` a
                   JOIN `service_occurrences` so ON a.`service_occurrence_id` = so.`id`
                   JOIN `service_templates` st ON so.`service_template_id` = st.`id`
                   JOIN `users` u ON a.`user_id` = u.`id`
                   $whereClause";

    $stmt = $db->prepare($statsQuery);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    $stmt->execute();
    $statistics = $stmt->fetch(PDO::FETCH_ASSOC);

    Helpers::sendResponse(true, 'Attendance history retrieved successfully', [
        'history' => $history,
        'statistics' => $statistics,
        'pagination' => [
            'total' => (int)$totalRecords,
            'current_page' => floor($offset / $limit) + 1,
            'limit' => $limit,
            'total_pages' => ceil($totalRecords / $limit)
        ],
        'user_permissions' => [
            'viewing_scope' => $viewingScope,
            'can_view_all' => $userPermissions['role_level'] >= 4
        ]
    ]);
} catch (PDOException $e) {
    ErrorLogger::logDatabaseError($e, $userData['user_id'] ?? 'unknown', [
        'endpoint' => 'attendance/history',
        'user_id' => $userData['user_id'] ?? 'unknown'
    ]);
    Helpers::sendResponse(false, 'Database error: ' . $e->getMessage(), null, 500);
} catch (Exception $e) {
    ErrorLogger::logError($e, [
        'endpoint' => 'attendance/history',
        'user_id' => $userData['user_id'] ?? 'unknown'
    ]);
    Helpers::sendResponse(false, 'Error: ' . $e->getMessage(), null, 500);
}
