<?php
require_once '../includes/auth.php';
require_once '../includes/db.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$action = $_POST['action'] ?? $data['action'] ?? $_GET['action'] ?? '';

$company_id = $_SESSION['company_id'];
$user_id = $_SESSION['user_id'];

// Helper to get employee info from user ID
function getEmployeeInfo($userId, $companyId) {
    return fetch("SELECT id, name, reporting_manager_id FROM employees WHERE user_id = ? AND company_id = ?", [$userId, $companyId]);
}

switch ($action) {
    case 'my_requests':
        $me = getEmployeeInfo($user_id, $company_id);
        if (!$me) {
            echo json_encode(['success' => false, 'message' => 'Employee profile not found']);
            exit;
        }

        $requests = fetchAll("
            SELECT r.*, m.name as manager_name 
            FROM overtime_requests r
            LEFT JOIN users m ON r.reporting_manager_id = m.id
            WHERE r.employee_id = ? AND r.company_id = ?
            ORDER BY r.date DESC, r.created_at DESC
        ", [$me['id'], $company_id]);

        echo json_encode(['success' => true, 'requests' => $requests]);
        break;

    case 'assigned_requests':
        // A manager sees requests where reporting_manager_id = user_id
        // Or if the user has role 'owner', they can see all pending/processed requests in the company
        if (hasRole('owner')) {
            $requests = fetchAll("
                SELECT r.*, e.name as employee_name, m.name as manager_name
                FROM overtime_requests r
                JOIN employees e ON r.employee_id = e.id
                LEFT JOIN users m ON r.reporting_manager_id = m.id
                WHERE r.company_id = ?
                ORDER BY r.date DESC, r.created_at DESC
            ", [$company_id]);
        } else {
            $requests = fetchAll("
                SELECT r.*, e.name as employee_name
                FROM overtime_requests r
                JOIN employees e ON r.employee_id = e.id
                WHERE r.company_id = ? AND r.reporting_manager_id = ?
                ORDER BY r.date DESC, r.created_at DESC
            ", [$company_id, $user_id]);
        }

        echo json_encode(['success' => true, 'requests' => $requests]);
        break;

    case 'update_status':
        $requestId = $_POST['id'] ?? $data['id'] ?? null;
        $status = $_POST['status'] ?? $data['status'] ?? '';
        $comments = $_POST['comments'] ?? $data['comments'] ?? null;

        if (!$requestId || !in_array($status, ['approved', 'rejected'])) {
            echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
            exit;
        }

        // Fetch request
        $request = fetch("SELECT * FROM overtime_requests WHERE id = ? AND company_id = ?", [$requestId, $company_id]);
        if (!$request) {
            echo json_encode(['success' => false, 'message' => 'Request not found']);
            exit;
        }

        // Access control: only owner or the assigned reporting manager can approve/reject
        if (!hasRole('owner') && $request['reporting_manager_id'] != $user_id) {
            echo json_encode(['success' => false, 'message' => 'Unauthorized to update this request']);
            exit;
        }

        try {
            query(
                "UPDATE overtime_requests SET status = ?, comments = ? WHERE id = ?",
                [$status, $comments, $requestId]
            );

            logAudit('Overtime Request Updated', "Request ID $requestId status updated to $status.");
            echo json_encode(['success' => true, 'message' => 'Overtime request status updated successfully']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}
