<?php

namespace App\Controllers;

use App\Core\Controller;

class LogController extends Controller
{
    public function index()
    {
        $this->requireAuth();

        $logModel = $this->model('LogModel');

        // Handle search and filtering
        $searchTerm = $_GET['search'] ?? '';
        $dateFrom = $_GET['date_from'] ?? '';
        $dateTo = $_GET['date_to'] ?? '';
        $category = $_GET['category'] ?? 'all';
        $page = $_GET['page'] ?? 1;
        $limit = 50;
        $offset = ($page - 1) * $limit;

        $data = [
            'logs' => [],
            'formatted_logs' => [],
            'error_logs' => [],
            'search' => $searchTerm,
            'date_from' => $dateFrom,
            'date_to' => $dateTo,
            'category' => $category,
            'page' => $page
        ];

        if ($category === 'error') {
            $data['error_logs'] = $this->parseErrorLog();
        } else {
            if ($searchTerm || $dateFrom || $dateTo) {
                $logs = $logModel->searchLogs($searchTerm, $dateFrom, $dateTo);
            } else {
                if ($category !== 'all') {
                    $logs = $logModel->getLogsByCategory($category, $limit, $offset);
                } else {
                    $logs = $logModel->getLogs($limit, $offset);
                }
            }
            $data['logs'] = $logs;
            $data['formatted_logs'] = $this->formatLogs($logs);
        }

        // Check if it's an AJAX request
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            $this->partial('logs/partials/log_content', $data);
        } else {
            $this->view('logs/index', $data);
        }
    }

    public function export()
    {
        $this->requireAuth();

        $logModel = $this->model('LogModel');
        $logs = $logModel->getLogs(10000); // Get more logs for export

        // Create plain text export
        header('Content-Type: text/plain');
        header('Content-Disposition: attachment; filename="activity_logs_' . date('Y-m-d_H-i-s') . '.txt"');

        echo "H&S INVENTORY MANAGEMENT SYSTEM - ACTIVITY LOG\n";
        echo "Generated: " . date('Y-m-d H:i:s') . "\n";
        echo "Generated by: " . $_SESSION['username'] . "\n";
        echo str_repeat("=", 80) . "\n\n";

        foreach ($logs as $log) {
            echo date('Y-m-d H:i:s', strtotime($log['created_at'])) . " - ";
            echo $log['username'] . " - ";
            echo $log['action'];
            if ($log['details']) {
                echo " - " . $log['details'];
            }
            echo " (IP: " . $log['ip_address'] . ")\n";
        }

        $this->addLog("Logs exported", "Exported " . count($logs) . " log entries");
        exit();
    }

    public function clear()
    {
        $this->requireAuth();

        // Only admins can clear logs
        if ($_SESSION['role'] !== 'admin') {
            $this->redirect('/activity-logs');
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            csrf_check();
            $daysToKeep = $_POST['days_to_keep'] ?? 30;

            $sql = "DELETE FROM activity_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL :days DAY)";
            $stmt = $this->db->prepare($sql);
            $stmt->execute(['days' => $daysToKeep]);

            $deletedCount = $stmt->rowCount();

            $this->addLog("Logs cleared", "Deleted " . $deletedCount . " log entries older than " . $daysToKeep . " days");
            $_SESSION['success'] = 'Deleted ' . $deletedCount . ' old log entries';
        }

        $this->redirect('/activity-logs');
    }

    private function formatLogs($logs)
    {
        $formatted = [];

        foreach ($logs as $log) {
            $timestamp = date('Y-m-d H:i:s', strtotime($log['created_at']));
            $text = $timestamp . " - " . $log['username'] . " " . $log['action'];

            if ($log['details']) {
                $text .= ": " . $log['details'];
            }

            $formatted[] = $text;
        }

        return $formatted;
    }
    private function parseErrorLog()
    {
        $errorLogFile = APP_ROOT . '/logs/error.log';
        if (!file_exists($errorLogFile)) {
            return [];
        }

        $content = file_get_contents($errorLogFile);
        $lines = explode("\n", $content);
        $errors = [];
        $pattern = '/\[(.*?)\] (.*?): (.*?) in (.*?) on line (\d+)/';

        foreach ($lines as $line) {
            if (preg_match($pattern, $line, $matches)) {
                $errors[] = [
                    'timestamp' => $matches[1],
                    'type' => $matches[2],
                    'message' => $matches[3],
                    'file' => $matches[4],
                    'line' => $matches[5],
                ];
            }
        }

        return array_reverse($errors); // Show most recent errors first
    }
}
