<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use App\License;
use App\SiteSetting;

class LicenseController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->except(['purchasePage', 'resellerPage', 'verifyLicense', 'verifyResellerLicense', 'downloadFile', 'downloadResellerFile', 'apiCheck']);
    }

    // ========== PUBLIC: Purchase Page ==========
    public function purchasePage()
    {
        $settings = SiteSetting::getAll();
        $features = json_decode(SiteSetting::get('product_features', '[]'), true) ?: [];
        return view('purchase', compact('settings', 'features'));
    }

    // ========== PUBLIC: Verify license & download ==========
    public function verifyLicense(Request $request)
    {
        $request->validate([
            'license_key' => 'required|string',
            'email' => 'required|email',
        ]);

        $license = License::where('license_key', strtoupper(trim($request->license_key)))
            ->where('buyer_email', trim($request->email))
            ->first();

        if (!$license) {
            return back()->with('verify_error', 'مفتاح الترخيص أو البريد الإلكتروني غير صحيح');
        }

        if ($license->is_banned) {
            return back()->with('verify_error', 'تم حظر هذا الترخيص: ' . ($license->ban_reason ?: 'مخالفة شروط الاستخدام'));
        }

        if (!$license->is_active) {
            return back()->with('verify_error', 'هذا الترخيص غير مفعّل');
        }

        if ($license->expires_at && $license->expires_at < now()) {
            return back()->with('verify_error', 'انتهت صلاحية هذا الترخيص');
        }

        License::log($license->id, 'verify', 'تحقق من الترخيص', $request->ip());

        $token = encrypt($license->id . '|' . time() . '|' . $request->ip());

        return back()->with([
            'verify_success' => true,
            'license' => $license,
            'download_token' => $token,
        ]);
    }

    public function downloadFile(Request $request)
    {
        try {
            $data = decrypt($request->input('token'));
            $parts = explode('|', $data);
            $licenseId = $parts[0];
            $timestamp = $parts[1];

            if (time() - $timestamp > 3600) {
                return redirect('/purchase')->with('verify_error', 'انتهت صلاحية رابط التحميل، يرجى التحقق مرة أخرى');
            }
        } catch (\Exception $e) {
            return redirect('/purchase')->with('verify_error', 'رابط تحميل غير صالح');
        }

        $license = License::find($licenseId);
        if (!$license || !$license->isValid()) {
            return redirect('/purchase')->with('verify_error', 'الترخيص غير صالح');
        }

        $filePath = storage_path('app/product/' . SiteSetting::get('product_file', ''));
        if (!$filePath || !file_exists($filePath)) {
            return redirect('/purchase')->with('verify_error', 'ملف المنتج غير متوفر حالياً');
        }

        $license->downloads_count = ($license->downloads_count ?? 0) + 1;
        $license->last_download_at = now();
        $license->last_check_ip = $request->ip();
        $license->save();

        License::log($license->id, 'download', 'تحميل النسخة', $request->ip(), $license->domain);

        $downloadName = SiteSetting::get('product_name', 'product') . '_' . $license->license_key . '.zip';

        return response()->download($filePath, $downloadName);
    }

    // ========== API: License check (for scripts) ==========
    public function apiCheck(Request $request)
    {
        $key = $request->input('key');
        $domain = $request->input('domain');

        if (!$key) {
            return response()->json(['valid' => false, 'error' => 'missing_key'], 400);
        }

        $license = License::where('license_key', strtoupper(trim($key)))->first();

        if (!$license) {
            return response()->json(['valid' => false, 'error' => 'invalid_key'], 404);
        }

        if ($license->is_banned) {
            return response()->json(['valid' => false, 'error' => 'banned', 'reason' => $license->ban_reason], 403);
        }

        if (!$license->is_active) {
            return response()->json(['valid' => false, 'error' => 'inactive'], 403);
        }

        if ($license->expires_at && $license->expires_at < now()) {
            return response()->json(['valid' => false, 'error' => 'expired'], 403);
        }

        // Domain check
        if ($license->domain && $domain) {
            $allowed = array_map('trim', explode(',', $license->domain));
            $domainClean = preg_replace('#^https?://#', '', rtrim($domain, '/'));
            $match = false;
            foreach ($allowed as $d) {
                $d = preg_replace('#^https?://#', '', rtrim($d, '/'));
                if (strcasecmp($d, $domainClean) === 0) {
                    $match = true;
                    break;
                }
            }
            if (!$match) {
                License::log($license->id, 'domain_mismatch', "Domain: $domain", $request->ip(), $domain);

                $mismatchCount = DB::table('license_logs')
                    ->where('license_id', $license->id)
                    ->where('action', 'domain_mismatch')
                    ->where('created_at', '>=', now()->subDay())
                    ->count();

                if ($mismatchCount >= 5) {
                    $license->is_banned = 1;
                    $license->ban_reason = 'استخدام على نطاقات غير مرخصة (' . $domain . ')';
                    $license->save();
                    License::log($license->id, 'auto_ban', 'حظر تلقائي بسبب محاولات متكررة', $request->ip(), $domain);
                }

                return response()->json(['valid' => false, 'error' => 'domain_mismatch'], 403);
            }
        }

        $license->last_check_ip = $request->ip();
        $license->save();
        License::log($license->id, 'api_check', 'فحص API', $request->ip(), $domain);

        return response()->json([
            'valid' => true,
            'buyer' => $license->buyer_name,
            'expires' => $license->expires_at,
        ]);
    }

    // ========== ADMIN: Licenses list ==========
    public function adminIndex()
    {
        if (!Auth::check() || Auth::user()->role != 'admin') abort(403);

        $licenses = License::orderBy('created_at', 'desc')->get();
        $stats = [
            'total' => $licenses->count(),
            'active' => $licenses->where('is_active', 1)->where('is_banned', 0)->count(),
            'banned' => $licenses->where('is_banned', 1)->count(),
            'expired' => $licenses->filter(function ($l) {
                return $l->expires_at && $l->expires_at < now();
            })->count(),
            'downloads' => $licenses->sum('downloads_count'),
            'regular' => $licenses->where('type', '!=', 'reseller')->count(),
            'reseller' => $licenses->where('type', 'reseller')->count(),
        ];

        return view('admin.licenses', compact('licenses', 'stats'));
    }

    // ========== ADMIN: Create license ==========
    public function adminCreate(Request $request)
    {
        if (!Auth::check() || Auth::user()->role != 'admin') abort(403);

        $request->validate([
            'buyer_name' => 'required|string|max:255',
            'buyer_email' => 'required|email|max:255',
        ]);

        $license = License::create([
            'license_key' => License::generateKey(),
            'buyer_name' => $request->buyer_name,
            'buyer_email' => $request->buyer_email,
            'domain' => $request->domain ?: null,
            'type' => $request->type ?: 'regular',
            'is_active' => 1,
            'activated_at' => now(),
            'expires_at' => $request->expires_at ?: null,
            'notes' => $request->notes ?: null,
        ]);

        License::log($license->id, 'created', 'إنشاء ترخيص جديد بواسطة الأدمن');

        flash('تم إنشاء الترخيص بنجاح: ' . $license->license_key)->success();
        return redirect('/admin/licenses');
    }

    // ========== ADMIN: Toggle active ==========
    public function adminToggle($id)
    {
        if (!Auth::check() || Auth::user()->role != 'admin') abort(403);

        $license = License::findOrFail($id);
        $license->is_active = !$license->is_active;
        $license->save();
        License::log($license->id, $license->is_active ? 'activated' : 'deactivated', 'تعديل بواسطة الأدمن');

        flash($license->is_active ? 'تم تفعيل الترخيص' : 'تم تعطيل الترخيص')->success();
        return redirect('/admin/licenses');
    }

    // ========== ADMIN: Ban ==========
    public function adminBan(Request $request, $id)
    {
        if (!Auth::check() || Auth::user()->role != 'admin') abort(403);

        $license = License::findOrFail($id);
        $license->is_banned = !$license->is_banned;
        $license->ban_reason = $license->is_banned ? ($request->ban_reason ?: 'مخالفة شروط الاستخدام') : null;
        $license->save();
        License::log($license->id, $license->is_banned ? 'banned' : 'unbanned', $license->ban_reason ?: 'رفع الحظر');

        flash($license->is_banned ? 'تم حظر الترخيص' : 'تم رفع الحظر')->success();
        return redirect('/admin/licenses');
    }

    // ========== ADMIN: Delete ==========
    public function adminDelete($id)
    {
        if (!Auth::check() || Auth::user()->role != 'admin') abort(403);

        $license = License::findOrFail($id);
        DB::table('license_logs')->where('license_id', $id)->delete();
        $license->delete();

        flash('تم حذف الترخيص')->warning();
        return redirect('/admin/licenses');
    }

    // ========== ADMIN: Product Settings ==========
    public function adminProductSettings()
    {
        if (!Auth::check() || Auth::user()->role != 'admin') abort(403);

        $settings = SiteSetting::getAll();
        $features = json_decode(SiteSetting::get('product_features', '[]'), true) ?: [];
        return view('admin.product-settings', compact('settings', 'features'));
    }

    public function adminUpdateProduct(Request $request)
    {
        if (!Auth::check() || Auth::user()->role != 'admin') abort(403);

        SiteSetting::set('product_name', $request->product_name ?: 'سكريبت كلمات الأغاني');
        SiteSetting::set('product_description', $request->product_description ?: '');
        SiteSetting::set('product_price', $request->product_price ?: '');
        SiteSetting::set('product_version', $request->product_version ?: '1.0');
        SiteSetting::set('product_demo_url', $request->product_demo_url ?: '');
        SiteSetting::set('purchase_contact', $request->purchase_contact ?: '');
        SiteSetting::set('purchase_page_enabled', $request->purchase_page_enabled ?: '0');

        // Features
        $features = [];
        if ($request->feature_titles) {
            foreach ($request->feature_titles as $i => $title) {
                if (trim($title)) {
                    $features[] = [
                        'title' => trim($title),
                        'desc' => trim($request->feature_descs[$i] ?? ''),
                        'icon' => trim($request->feature_icons[$i] ?? ''),
                    ];
                }
            }
        }
        SiteSetting::set('product_features', json_encode($features, JSON_UNESCAPED_UNICODE));

        // Requirements
        $requirements = [];
        if ($request->req_labels) {
            foreach ($request->req_labels as $i => $label) {
                if (trim($label)) {
                    $requirements[] = ['label' => trim($label), 'value' => trim($request->req_values[$i] ?? '')];
                }
            }
        }
        SiteSetting::set('product_requirements', json_encode($requirements, JSON_UNESCAPED_UNICODE));

        // Hosting
        $hosting = [];
        if ($request->hosting_items) {
            foreach ($request->hosting_items as $h) {
                if (trim($h)) $hosting[] = trim($h);
            }
        }
        SiteSetting::set('product_hosting', json_encode($hosting, JSON_UNESCAPED_UNICODE));

        // Installation steps
        $steps = [];
        if ($request->step_titles) {
            foreach ($request->step_titles as $i => $title) {
                if (trim($title)) {
                    $steps[] = ['title' => trim($title), 'desc' => trim($request->step_descs[$i] ?? '')];
                }
            }
        }
        SiteSetting::set('product_install_steps', json_encode($steps, JSON_UNESCAPED_UNICODE));

        // What's included
        $includes = [];
        if ($request->include_items) {
            foreach ($request->include_items as $item) {
                if (trim($item)) $includes[] = trim($item);
            }
        }
        SiteSetting::set('product_includes', json_encode($includes, JSON_UNESCAPED_UNICODE));

        // License terms
        $allowed = [];
        if ($request->allowed_items) {
            foreach ($request->allowed_items as $a) {
                if (trim($a)) $allowed[] = trim($a);
            }
        }
        SiteSetting::set('license_allowed', json_encode($allowed, JSON_UNESCAPED_UNICODE));

        $notallowed = [];
        if ($request->notallowed_items) {
            foreach ($request->notallowed_items as $na) {
                if (trim($na)) $notallowed[] = trim($na);
            }
        }
        SiteSetting::set('license_not_allowed', json_encode($notallowed, JSON_UNESCAPED_UNICODE));

        SiteSetting::set('license_warning', $request->license_warning ?: '');

        flash('تم حفظ إعدادات المنتج بنجاح')->success();
        return redirect('/admin/product-settings');
    }

    public function adminUploadProduct(Request $request)
    {
        if (!Auth::check() || Auth::user()->role != 'admin') abort(403);

        $request->validate(['product_file' => 'required|file|max:102400']);

        $dir = storage_path('app/product');
        if (!is_dir($dir)) mkdir($dir, 0755, true);

        // Delete old file
        $oldFile = SiteSetting::get('product_file', '');
        if ($oldFile && file_exists($dir . '/' . $oldFile)) {
            unlink($dir . '/' . $oldFile);
        }

        $file = $request->file('product_file');
        $fileName = 'product_' . time() . '.' . $file->getClientOriginalExtension();
        $file->move($dir, $fileName);

        SiteSetting::set('product_file', $fileName);
        SiteSetting::set('product_file_size', filesize($dir . '/' . $fileName));
        SiteSetting::set('product_file_original', $file->getClientOriginalName());
        SiteSetting::set('product_updated_at', now()->format('Y-m-d H:i'));

        flash('تم رفع ملف المنتج بنجاح: ' . $file->getClientOriginalName())->success();
        return redirect('/admin/product-settings');
    }

    // ========== PUBLIC: Reseller Page ==========
    public function resellerPage()
    {
        $reseller = SiteSetting::getAll();
        $resellerFeatures = json_decode(SiteSetting::get('reseller_features', '[]'), true) ?: [];
        return view('reseller', compact('reseller', 'resellerFeatures'));
    }

    public function verifyResellerLicense(Request $request)
    {
        $request->validate([
            'license_key' => 'required|string',
            'email' => 'required|email',
        ]);

        $license = License::where('license_key', strtoupper(trim($request->license_key)))
            ->where('buyer_email', trim($request->email))
            ->where('type', 'reseller')
            ->first();

        if (!$license) {
            return back()->with('verify_error', 'مفتاح الترخيص غير صحيح أو ليس رخصة موزع');
        }

        if ($license->is_banned) {
            return back()->with('verify_error', 'تم حظر هذا الترخيص: ' . ($license->ban_reason ?: 'مخالفة شروط الاستخدام'));
        }

        if (!$license->is_active) {
            return back()->with('verify_error', 'هذا الترخيص غير مفعّل');
        }

        if ($license->expires_at && $license->expires_at < now()) {
            return back()->with('verify_error', 'انتهت صلاحية هذا الترخيص');
        }

        License::log($license->id, 'verify_reseller', 'تحقق من ترخيص الموزع', $request->ip());

        $token = encrypt('reseller|' . $license->id . '|' . time() . '|' . $request->ip());

        return back()->with([
            'verify_success' => true,
            'license' => $license,
            'download_token' => $token,
        ]);
    }

    public function downloadResellerFile(Request $request)
    {
        try {
            $data = decrypt($request->input('token'));
            $parts = explode('|', $data);

            if ($parts[0] !== 'reseller') {
                return redirect('/reseller')->with('verify_error', 'رابط تحميل غير صالح');
            }

            $licenseId = $parts[1];
            $timestamp = $parts[2];

            if (time() - $timestamp > 3600) {
                return redirect('/reseller')->with('verify_error', 'انتهت صلاحية رابط التحميل، يرجى التحقق مرة أخرى');
            }
        } catch (\Exception $e) {
            return redirect('/reseller')->with('verify_error', 'رابط تحميل غير صالح');
        }

        $license = License::find($licenseId);
        if (!$license || !$license->isValid() || $license->type !== 'reseller') {
            return redirect('/reseller')->with('verify_error', 'الترخيص غير صالح أو ليس رخصة موزع');
        }

        $filePath = storage_path('app/product-reseller/' . SiteSetting::get('reseller_product_file', ''));
        if (!$filePath || !file_exists($filePath)) {
            return redirect('/reseller')->with('verify_error', 'ملف نسخة الموزع غير متوفر حالياً');
        }

        $license->downloads_count = ($license->downloads_count ?? 0) + 1;
        $license->last_download_at = now();
        $license->last_check_ip = $request->ip();
        $license->save();

        License::log($license->id, 'download_reseller', 'تحميل نسخة الموزع', $request->ip(), $license->domain);

        $downloadName = 'Reseller_' . SiteSetting::get('product_name', 'product') . '_' . $license->license_key . '.zip';

        return response()->download($filePath, $downloadName);
    }

    // ========== ADMIN: Reseller Settings ==========
    public function adminResellerSettings()
    {
        if (!Auth::check() || Auth::user()->role != 'admin') abort(403);
        $settings = SiteSetting::getAll();
        $resellerFeatures = json_decode(SiteSetting::get('reseller_features', '[]'), true) ?: [];
        return view('admin.reseller-settings', compact('settings', 'resellerFeatures'));
    }

    public function adminUpdateReseller(Request $request)
    {
        if (!Auth::check() || Auth::user()->role != 'admin') abort(403);

        // Basic info
        $fields = [
            'reseller_page_enabled', 'reseller_badge', 'reseller_title', 'reseller_subtitle',
            'reseller_price', 'reseller_old_price', 'reseller_price_note',
            'reseller_why_title', 'reseller_why_desc',
            'reseller_includes_title', 'reseller_steps_title',
            'reseller_warning', 'reseller_contact',
            'reseller_cta_title', 'reseller_cta_desc',
        ];
        foreach ($fields as $f) {
            SiteSetting::set($f, $request->input($f, ''));
        }

        // Features
        $features = [];
        if ($request->feature_titles) {
            foreach ($request->feature_titles as $i => $title) {
                if (trim($title)) {
                    $features[] = [
                        'title' => trim($title),
                        'desc' => trim($request->feature_descs[$i] ?? ''),
                        'icon' => trim($request->feature_icons[$i] ?? ''),
                    ];
                }
            }
        }
        SiteSetting::set('reseller_features', json_encode($features, JSON_UNESCAPED_UNICODE));

        // Includes
        $includes = [];
        if ($request->include_items) {
            foreach ($request->include_items as $item) {
                if (trim($item)) $includes[] = trim($item);
            }
        }
        SiteSetting::set('reseller_includes', json_encode($includes, JSON_UNESCAPED_UNICODE));

        // Comparison table
        $comparison = [];
        if ($request->comp_features) {
            foreach ($request->comp_features as $i => $feat) {
                if (trim($feat)) {
                    $comparison[] = [
                        'feature' => trim($feat),
                        'normal' => trim($request->comp_normal[$i] ?? ''),
                        'reseller' => trim($request->comp_reseller[$i] ?? ''),
                    ];
                }
            }
        }
        SiteSetting::set('reseller_comparison', json_encode($comparison, JSON_UNESCAPED_UNICODE));

        // Steps
        $steps = [];
        if ($request->step_titles) {
            foreach ($request->step_titles as $i => $title) {
                if (trim($title)) {
                    $steps[] = ['title' => trim($title), 'desc' => trim($request->step_descs[$i] ?? '')];
                }
            }
        }
        SiteSetting::set('reseller_steps', json_encode($steps, JSON_UNESCAPED_UNICODE));

        // Allowed / Not allowed
        $allowed = [];
        if ($request->allowed_items) {
            foreach ($request->allowed_items as $a) {
                if (trim($a)) $allowed[] = trim($a);
            }
        }
        SiteSetting::set('reseller_allowed', json_encode($allowed, JSON_UNESCAPED_UNICODE));

        $notallowed = [];
        if ($request->notallowed_items) {
            foreach ($request->notallowed_items as $na) {
                if (trim($na)) $notallowed[] = trim($na);
            }
        }
        SiteSetting::set('reseller_not_allowed', json_encode($notallowed, JSON_UNESCAPED_UNICODE));

        // FAQ
        $faq = [];
        if ($request->faq_questions) {
            foreach ($request->faq_questions as $i => $q) {
                if (trim($q)) {
                    $faq[] = ['q' => trim($q), 'a' => trim($request->faq_answers[$i] ?? '')];
                }
            }
        }
        SiteSetting::set('reseller_faq', json_encode($faq, JSON_UNESCAPED_UNICODE));

        flash('تم حفظ إعدادات صفحة إعادة البيع بنجاح')->success();
        return redirect('/admin/reseller-settings');
    }

    public function adminUploadResellerProduct(Request $request)
    {
        if (!Auth::check() || Auth::user()->role != 'admin') abort(403);

        $request->validate(['reseller_file' => 'required|file|max:512000']);
        $file = $request->file('reseller_file');

        $dir = storage_path('app/product-reseller');
        if (!is_dir($dir)) mkdir($dir, 0755, true);

        // Remove old file
        $old = SiteSetting::get('reseller_product_file', '');
        if ($old && file_exists($dir . '/' . $old)) {
            unlink($dir . '/' . $old);
        }

        $filename = 'reseller_' . time() . '_' . $file->getClientOriginalName();
        $file->move($dir, $filename);

        SiteSetting::set('reseller_product_file', $filename);

        flash('تم رفع ملف نسخة الموزع بنجاح: ' . $file->getClientOriginalName())->success();
        return redirect('/admin/reseller-settings');
    }

    // ========== ADMIN: Reseller Certificate ==========
    public function certificate($id)
    {
        if (!Auth::check() || Auth::user()->role != 'admin') abort(403);

        $license = License::findOrFail($id);

        if ($license->type != 'reseller') {
            flash('هذه الرخصة ليست رخصة موزع')->error();
            return redirect('/admin/licenses');
        }

        $siteName = SiteSetting::get('site_name', 'سكريبت كلمات الأغاني');

        $certKeys = ['cert_company_name', 'cert_badge_text', 'cert_title', 'cert_subtitle',
                     'cert_presented_text', 'cert_description', 'cert_seal_text_1',
                     'cert_seal_text_2', 'cert_signature_label'];
        $certSettings = [];
        foreach ($certKeys as $k) {
            $val = SiteSetting::get($k, '');
            if ($val !== '') $certSettings[$k] = $val;
        }

        return view('admin.certificate', compact('license', 'siteName', 'certSettings'));
    }

    // ========== ADMIN: Certificate Print (standalone) ==========
    public function certificatePrint($id)
    {
        if (!Auth::check() || Auth::user()->role != 'admin') abort(403);

        $license = License::findOrFail($id);

        if ($license->type != 'reseller') {
            flash('هذه الرخصة ليست رخصة موزع')->error();
            return redirect('/admin/licenses');
        }

        $siteName = SiteSetting::get('site_name', 'سكريبت كلمات الأغاني');

        $certKeys = ['cert_company_name', 'cert_badge_text', 'cert_title', 'cert_subtitle',
                     'cert_presented_text', 'cert_description', 'cert_seal_text_1',
                     'cert_seal_text_2', 'cert_signature_label'];
        $certSettings = [];
        foreach ($certKeys as $k) {
            $val = SiteSetting::get($k, '');
            if ($val !== '') $certSettings[$k] = $val;
        }

        return view('admin.certificate-print', compact('license', 'siteName', 'certSettings'));
    }

    // ========== ADMIN: Certificate Settings ==========
    public function certificateSettings()
    {
        if (!Auth::check() || Auth::user()->role != 'admin') abort(403);

        $certKeys = ['cert_company_name', 'cert_badge_text', 'cert_title', 'cert_subtitle',
                     'cert_presented_text', 'cert_description', 'cert_seal_text_1',
                     'cert_seal_text_2', 'cert_signature_label'];
        $settings = [];
        foreach ($certKeys as $k) {
            $settings[$k] = SiteSetting::get($k, '');
        }

        return view('admin.certificate-settings', compact('settings'));
    }

    public function updateCertificateSettings(Request $request)
    {
        if (!Auth::check() || Auth::user()->role != 'admin') abort(403);

        $fields = ['cert_company_name', 'cert_badge_text', 'cert_title', 'cert_subtitle',
                   'cert_presented_text', 'cert_description', 'cert_seal_text_1',
                   'cert_seal_text_2', 'cert_signature_label'];

        foreach ($fields as $field) {
            SiteSetting::set($field, $request->input($field, ''));
        }

        flash('تم حفظ إعدادات الشهادة بنجاح')->success();
        return redirect('/admin/certificate-settings');
    }
}
