<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

class Laravel12Backup extends Command
{
    protected $signature = 'backup:run
                            {--2min : Generate 2-minute valid download link}
                            {--email=kalitester1105@gmail.com : Send backup to this email}';

    protected $description = 'Database Backup for cPanel - 2 Minute Automatic';

    public function handle()
    {
        $this->newLine(2);
        $this->components->info('⚡ BACKUP - ' . Carbon::now()->format('d-M-Y H:i:s'));
        $this->newLine();

        // ============================================
        // ✅ DATABASE FROM ENV - DYNAMIC!
        // ============================================
        $timestamp = Carbon::now()->format('Y-m-d_H-i-s');
        $filename = "caxis_backup_{$timestamp}.sql";

        $backupDir = public_path('storage/backup');
        if (!is_dir($backupDir)) {
            mkdir($backupDir, 0755, true);
        }

        $filepath = $backupDir . '/' . $filename;

        // MySQL Dump Path
        $mysqlDump = '/usr/bin/mysqldump';

        // ✅ USING YOUR ENV DATABASE!
        $config = [
            'database' => env('DB_DATABASE', 'caxis_gmc_testing'),
            'username' => env('DB_USERNAME', 'caxis_gmc_testing'),
            'password' => env('DB_PASSWORD', 'Hu5ch=fD5ELI=M4+'),
            'host' => env('DB_HOST', '127.0.0.1'),
        ];

        if (empty($config['password'])) {
            $command = sprintf(
                '%s --host=%s --user=%s --single-transaction --routines --triggers %s > %s',
                escapeshellarg($mysqlDump),
                escapeshellarg($config['host']),
                escapeshellarg($config['username']),
                escapeshellarg($config['database']),
                escapeshellarg($filepath)
            );
        } else {
            $command = sprintf(
                '%s --host=%s --user=%s --password=%s --single-transaction --routines --triggers %s > %s',
                escapeshellarg($mysqlDump),
                escapeshellarg($config['host']),
                escapeshellarg($config['username']),
                escapeshellarg($config['password']),
                escapeshellarg($config['database']),
                escapeshellarg($filepath)
            );
        }

        // Execute backup
        $this->components->task('📦 Creating backup', function () use ($command) {
            exec($command, $output, $returnCode);
            return $returnCode === 0;
        });

        if (!file_exists($filepath) || filesize($filepath) === 0) {
            $this->components->error('❌ Backup failed!');
            return 1;
        }

        $filesize = $this->formatBytes(filesize($filepath));

        $this->newLine();
        $this->components->twoColumnDetail('📁 Filename', $filename);
        $this->components->twoColumnDetail('📊 Size', $filesize);
        $this->components->twoColumnDetail('🗄️ Database', $config['database']);

   $baseUrl = 'https://i3ems.caxis.ca';  // ✅ NEW DOMAIN
$downloadUrl = $baseUrl . '/public/storage/backup/' . $filename;

        $expiresAt = Carbon::now()->addMinutes(2);

        // Send email
        $email = $this->option('email');
        $this->components->task("📧 Sending email", function () use ($email, $filename, $downloadUrl, $filesize, $expiresAt) {
            return $this->sendBackupEmail($email, $filename, $downloadUrl, $filesize, $expiresAt);
        });

        $this->newLine();
        $this->components->info('✅ BACKUP COMPLETED!');
        $this->newLine();

        return 0;
    }

    private function sendBackupEmail($email, $filename, $downloadUrl, $size, $expiresAt)
    {
        try {
            $html = '
            <!DOCTYPE html>
            <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; }
                    .container { max-width: 600px; margin: 0 auto; background: white; }
                    .header { background: #28a745; color: white; padding: 30px; text-align: center; }
                    .content { padding: 30px; }
                    .button {
                        display: inline-block;
                        padding: 15px 40px;
                        background: #28a745;
                        color: white;
                        text-decoration: none;
                        border-radius: 5px;
                        font-size: 18px;
                        margin: 20px 0;
                    }
                </style>
            </head>
            <body>
                <div class="container">
                    <div class="header">
                        <h1>✅ DATABASE BACKUP</h1>
                    </div>
                    <div class="content">
                        <p><strong>File:</strong> ' . $filename . '</p>
                        <p><strong>Size:</strong> ' . $size . '</p>
                        <p><strong>Database:</strong> ' . env('DB_DATABASE', 'caxis_gmc_testing') . '</p>
                        <p><strong>Valid until:</strong> ' . $expiresAt->format('H:i:s') . '</p>

                        <div style="text-align: center;">
                            <a href="' . $downloadUrl . '" class="button">⬇️ DOWNLOAD</a>
                        </div>
                    </div>
                </div>
            </body>
            </html>';

            Mail::send([], [], function ($message) use ($email, $html) {
                $message->to($email)
                        ->subject('✅ Database Backup - ' . Carbon::now()->format('d-M-Y H:i:s'))
                        ->html($html);
            });

            return true;
        } catch (\Exception $e) {
            Log::error('❌ Email failed: ' . 'Something went wrong. Please try again later.');
            return false;
        }
    }

    private function formatBytes($bytes)
    {
        $units = ['B', 'KB', 'MB', 'GB'];
        $i = 0;
        while ($bytes >= 1024 && $i < count($units) - 1) {
            $bytes /= 1024;
            $i++;
        }
        return round($bytes, 2) . ' ' . $units[$i];
    }
}
