<?php

/**
 * ============================================
 * TICKETS.PHP - Admin Tickets Management API
 * ============================================
 */
require_once 'config/database.php';
require_once 'utils/helpers.php';

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

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

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

    // Verify admin/HOD access
    $query = "SELECT ur.role_level, ur.can_issue_tickets, ur.can_resolve_tickets 
              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();
    $userRole = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$userRole || !$userRole['can_issue_tickets']) {
        Helpers::sendResponse(false, 'Unauthorized. Ticket management access required.', null, 403);
    }

    // GET: Retrieve tickets
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $statusFilter = isset($_GET['status']) ? $_GET['status'] : 'all'; // all, open, resolved
        $severityFilter = isset($_GET['severity']) ? $_GET['severity'] : '';
        $userFilter = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
        $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50;
        $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;

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

        if ($statusFilter === 'open') {
            $whereConditions[] = "t.is_resolved = FALSE";
        } elseif ($statusFilter === 'resolved') {
            $whereConditions[] = "t.is_resolved = TRUE";
        }

        if ($severityFilter) {
            $whereConditions[] = "t.severity = :severity";
            $params[':severity'] = $severityFilter;
        }

        if ($userFilter > 0) {
            $whereConditions[] = "t.user_id = :user_id";
            $params[':user_id'] = $userFilter;
        }

        $whereClause = count($whereConditions) > 0 ? 'WHERE ' . implode(' AND ', $whereConditions) : '';

        $query = "SELECT t.id, t.ticket_number, t.user_id, t.ticket_type, t.reason, 
                         t.severity, t.issued_at, t.is_resolved, t.resolved_at, 
                         t.resolution_notes, t.created_at,
                         CONCAT(u.first_name, ' ', u.last_name) as user_name,
                         u.email as user_email,
                         d.name as department_name,
                         CONCAT(ib.first_name, ' ', ib.last_name) as issued_by_name,
                         CONCAT(rb.first_name, ' ', rb.last_name) as resolved_by_name
                  FROM tickets t
                  JOIN users u ON t.user_id = u.id
                  LEFT JOIN departments d ON u.department_id = d.id
                  JOIN users ib ON t.issued_by = ib.id
                  LEFT JOIN users rb ON t.resolved_by = rb.id
                  $whereClause
                  ORDER BY t.issued_at 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();

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

        Helpers::sendResponse(true, 'Tickets retrieved successfully', [
            'tickets' => $tickets,
            'count' => count($tickets)
        ]);
    }

    // POST: Create new ticket
    elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $data = json_decode(file_get_contents("php://input"));

        // Validate required fields
        if (empty($data->user_id) || empty($data->reason)) {
            Helpers::sendResponse(false, 'User ID and reason are required', null, 400);
        }

        // Verify user exists
        $query = "SELECT id, first_name, last_name FROM users WHERE id = :user_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':user_id', $data->user_id);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            Helpers::sendResponse(false, 'User not found', null, 404);
        }

        // Generate ticket number
        $ticketNumber = 'TKT-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));

        // Insert new ticket
        $query = "INSERT INTO tickets 
                  (ticket_number, user_id, issued_by, ticket_type, reason, severity, issued_at, created_at) 
                  VALUES 
                  (:ticket_number, :user_id, :issued_by, :ticket_type, :reason, :severity, NOW(), NOW())";

        $stmt = $db->prepare($query);
        $stmt->bindParam(':ticket_number', $ticketNumber);
        $stmt->bindParam(':user_id', $data->user_id);
        $stmt->bindParam(':issued_by', $userData['user_id']);
        $ticketType = $data->ticket_type ?? 'warning';
        $stmt->bindParam(':ticket_type', $ticketType);
        $stmt->bindParam(':reason', $data->reason);
        $severity = $data->severity ?? 'medium';
        $stmt->bindParam(':severity', $severity);

        if ($stmt->execute()) {
            $newTicketId = $db->lastInsertId();

            // Log admin activity
            $logQuery = "INSERT INTO admin_logs 
                        (admin_id, action, action_type, target_type, target_id, details, ip_address, created_at) 
                        VALUES 
                        (:admin_id, 'issue_ticket', 'create', 'ticket', :ticket_id, :details, :ip, NOW())";

            $details = json_encode([
                'ticket_number' => $ticketNumber,
                'user' => $user['first_name'] . ' ' . $user['last_name'],
                'severity' => $severity
            ]);
            $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

            $stmt = $db->prepare($logQuery);
            $stmt->bindParam(':admin_id', $userData['user_id']);
            $stmt->bindParam(':ticket_id', $newTicketId);
            $stmt->bindParam(':details', $details);
            $stmt->bindParam(':ip', $ip);
            $stmt->execute();

            Helpers::sendResponse(true, 'Ticket issued successfully', [
                'ticket_id' => $newTicketId,
                'ticket_number' => $ticketNumber
            ], 201);
        } else {
            Helpers::sendResponse(false, 'Failed to issue ticket', null, 500);
        }
    }

    // PATCH: Resolve ticket
    elseif ($_SERVER['REQUEST_METHOD'] === 'PATCH') {
        if (!$userRole['can_resolve_tickets']) {
            Helpers::sendResponse(false, 'Unauthorized. Ticket resolution access required.', null, 403);
        }

        $ticketId = isset($_GET['id']) ? intval($_GET['id']) : null;

        if (!$ticketId) {
            Helpers::sendResponse(false, 'Ticket ID is required', null, 400);
        }

        $data = json_decode(file_get_contents("php://input"));

        // Check if ticket exists and is not already resolved
        $query = "SELECT id, ticket_number, is_resolved FROM tickets WHERE id = :ticket_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':ticket_id', $ticketId);
        $stmt->execute();
        $ticket = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$ticket) {
            Helpers::sendResponse(false, 'Ticket not found', null, 404);
        }

        if ($ticket['is_resolved']) {
            Helpers::sendResponse(false, 'Ticket is already resolved', null, 400);
        }

        // Resolve ticket
        $query = "UPDATE tickets 
                  SET is_resolved = TRUE, resolved_at = NOW(), resolved_by = :resolved_by, 
                      resolution_notes = :resolution_notes, updated_at = NOW()
                  WHERE id = :ticket_id";

        $stmt = $db->prepare($query);
        $stmt->bindParam(':ticket_id', $ticketId);
        $stmt->bindParam(':resolved_by', $userData['user_id']);
        $resolutionNotes = $data->resolution_notes ?? '';
        $stmt->bindParam(':resolution_notes', $resolutionNotes);

        if ($stmt->execute()) {
            // Log admin activity
            $logQuery = "INSERT INTO admin_logs 
                        (admin_id, action, action_type, target_type, target_id, details, ip_address, created_at) 
                        VALUES 
                        (:admin_id, 'resolve_ticket', 'update', 'ticket', :ticket_id, :details, :ip, NOW())";

            $details = json_encode([
                'ticket_number' => $ticket['ticket_number'],
                'resolution_notes' => $resolutionNotes
            ]);
            $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

            $stmt = $db->prepare($logQuery);
            $stmt->bindParam(':admin_id', $userData['user_id']);
            $stmt->bindParam(':ticket_id', $ticketId);
            $stmt->bindParam(':details', $details);
            $stmt->bindParam(':ip', $ip);
            $stmt->execute();

            Helpers::sendResponse(true, 'Ticket resolved successfully');
        } else {
            Helpers::sendResponse(false, 'Failed to resolve ticket', null, 500);
        }
    }

    // DELETE: Delete ticket
    elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
        $ticketId = isset($_GET['id']) ? intval($_GET['id']) : null;

        if (!$ticketId) {
            Helpers::sendResponse(false, 'Ticket ID is required', null, 400);
        }

        // Get ticket info before deletion
        $query = "SELECT ticket_number FROM tickets WHERE id = :ticket_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':ticket_id', $ticketId);
        $stmt->execute();
        $ticket = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$ticket) {
            Helpers::sendResponse(false, 'Ticket not found', null, 404);
        }

        // Delete ticket
        $query = "DELETE FROM tickets WHERE id = :ticket_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':ticket_id', $ticketId);

        if ($stmt->execute()) {
            // Log admin activity
            $logQuery = "INSERT INTO admin_logs 
                        (admin_id, action, action_type, target_type, target_id, details, ip_address, created_at) 
                        VALUES 
                        (:admin_id, 'delete_ticket', 'delete', 'ticket', :ticket_id, :details, :ip, NOW())";

            $details = json_encode(['ticket_number' => $ticket['ticket_number']]);
            $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

            $stmt = $db->prepare($logQuery);
            $stmt->bindParam(':admin_id', $userData['user_id']);
            $stmt->bindParam(':ticket_id', $ticketId);
            $stmt->bindParam(':details', $details);
            $stmt->bindParam(':ip', $ip);
            $stmt->execute();

            Helpers::sendResponse(true, 'Ticket deleted successfully');
        } else {
            Helpers::sendResponse(false, 'Failed to delete ticket', null, 500);
        }
    } else {
        Helpers::sendResponse(false, 'Method not allowed', null, 405);
    }
} catch (PDOException $e) {
    ErrorLogger::logDatabaseError($e, $userData['user_id'] ?? 'unknown', [
        'endpoint' => 'admin/tickets',
        'user_id' => $userData['user_id'] ?? 'unknown'
    ]);
    Helpers::sendResponse(false, 'Database error in tickets management: ' . $e->getMessage(), null, 500);
} catch (Exception $e) {
    ErrorLogger::logError($e, [
        'endpoint' => 'admin/tickets',
        'user_id' => $userData['user_id'] ?? 'unknown'
    ]);
    Helpers::sendResponse(false, 'Error in tickets management: ' . $e->getMessage(), null, 500);
}
