<?php

namespace App\Http\Controllers;

use League\CommonMark\CommonMarkConverter;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class ChangeLogController extends BaseController
{
    /**
     * The filesystem implementation.
     *
     * @var Filesystem
     */
    protected $files;

    public function __construct(Filesystem $files)
    {
        $this->files = $files;
    }
    public function index()
    {
        $changelog = $this->getComprehensiveChangelog();
        
        //Return the view with the changelog data
        return View::make('changelog')->with('changelog', $changelog)->with('version', $this->getVersion());
    }
    public function getChangelog()
    {
        try {
            // Use git command to get tags sorted by version
            $output = shell_exec('git tag --sort=-version:refname 2>&1');
            
            if ($output === null) {
                Log::warning('Git command failed or not available');
                return [];
            }

            $tags = array_filter(explode("\n", trim($output)));
            $formattedTags = [];

            foreach (array_slice($tags, 0, 10) as $tagName) { // Limit to 10 most recent
                $tagName = trim($tagName);
                if (empty($tagName)) continue;

                // Get tag date and commit info
                $tagDate = shell_exec("git log -1 --format=%ai $tagName 2>&1");
                $tagMessage = shell_exec("git tag -l --format='%(contents)' $tagName 2>&1");
                $commitId = shell_exec("git rev-list -n 1 $tagName 2>&1");
                
                $formattedTags[] = (object)[
                    'name' => $tagName,
                    'message' => $tagMessage ? trim($tagMessage) : "Release $tagName",
                    'commit' => (object)[
                        'id' => $commitId ? trim($commitId) : '',
                        'created_at' => $tagDate ? trim($tagDate) : now()->toISOString()
                    ]
                ];
            }

            return $formattedTags;
        } catch (\Exception $e) {
            Log::error('Exception in getChangelog: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
            return [];
        }
    }
    public function getVersion()
    {
        try {
            return exec('git describe') ?: 'Unknown';
        } catch (\Exception $e) {
            Log::warning('Failed to get git version: ' . $e->getMessage());
            return 'Unknown';
        }
    }

    public function getComprehensiveChangelog()
    {
        return [
            [
                'title' => '🔧 Framework & Infrastructure Upgrades',
                'icon' => '🔧',
                'features' => [
                    'Migrated from Laravel 5.2 to Laravel 12 with syntax updates',
                    'Ensured MySQL 9 compatibility and optimized queries',
                    'Full Docker setup for development & production',
                    'Production optimization and cleanup'
                ]
            ],
            [
                'title' => '📞 3CX Telephony Integration',
                'icon' => '📞',
                'features' => [
                    'Implemented 3CX telephony system with API and CRM integration',
                    'Added call history, extension management, and templates',
                    'Fixed call hang and reliability issues'
                ]
            ],
            [
                'title' => '💼 External Integrations',
                'icon' => '💼',
                'features' => [
                    '<strong>Xero API Integration:</strong> now 1-click send invoices directly to Xero',
                    'Integrated Twilio for SMS & voice',
                    '<strong>Office 365 Calendar Integration</strong> for scheduling',
                    '<strong>Global SMTP settings</strong> for unified email sending'
                ]
            ],
            [
                'title' => '🔐 Security & Authentication',
                'icon' => '🔐',
                'features' => [
                    'Comprehensive CSRF protection',
                    'Redesigned modern login screen with mobile optimization',
                    'Improved authentication and login validation'
                ]
            ],
            [
                'title' => '🎨 UI/UX Improvements',
                'icon' => '🎨',
                'features' => [
                    'Modernized interface with responsive layouts',
                    '<strong>Large, prominent Clock In/Clock Out buttons</strong> for better visibility',
                    'Redesigned clock-in/out workflows',
                    'Vue.js integration for interactive components'
                ]
            ],
            [
                'title' => '📊 Business Process Management',
                'icon' => '📊',
                'features' => [
                    'Added sub-project and task management features',
                    'Refactored stock system with barcode and purchase order support',
                    'Improved booking system and client data handling'
                ]
            ],
            [
                'title' => '🔍 Search & Performance',
                'icon' => '🔍',
                'features' => [
                    'Enhanced search system and optimized performance',
                    'Fixed memory leaks, caching, and progressive loading'
                ]
            ],
            [
                'title' => '🐛 Bug Fixes & Maintenance',
                'icon' => '🐛',
                'features' => [
                    'Fixed notifications, clock-in/out, invoices, QA workflows',
                    'Resolved database migrations, client selection, and timezone issues',
                    'Cleaned up debug messages, JS, and CSS fixes'
                ]
            ],            
            [
                'title' => '📱 Mobile & Modern Features',
                'icon' => '📱',
                'features' => [
                    'Mobile UI improvements and responsive design',
                    'Enhanced REST APIs with better JSON responses'
                ]
            ]
        ];
    }
}
