<?php

namespace App\Http\Controllers\Admin;

use App\Models\Template;
use Illuminate\Http\Request;
use App\Models\GeneralSetting;
use Illuminate\Support\Carbon;
use App\Models\ResellerSiteInfo;
use App\Models\SiteConfiguration;
use App\Http\Controllers\Controller;
use App\Services\FacebookConversionService;
use Illuminate\Support\Facades\Http;
use Symfony\Component\HttpFoundation\StreamedResponse;

class GeneralSettingController extends Controller
{
    public function get_site_info()
    {
        $setting = GeneralSetting::first();
        if ($setting) {
            return response()->json([
                "status" => "OK",
                "setting" => $setting,
            ]);
        }
    }
    public function get_configuration_info()
    {
        $setting = SiteConfiguration::first();
        if ($setting) {
            return response()->json([
                "status" => true,
                "setting" => $setting,
            ]);
        }
    }


    public function edit_configuration_info(Request $request)
    {

        $validatedData = $request->validate([
            'show_city_sub_city'      => 'nullable',
            'show_stock_out'          => 'nullable',
            'variant_stock_active'    => 'nullable',
            'card_row'                => 'nullable',
            'show_checkout_note'      => 'nullable',
            'show_reseller_panel'     => 'nullable',
            'show_reseller_shop'      => 'nullable',
            'is_pre_stock'            => 'nullable',
            'stock_manage'            => 'nullable',
            'disable_order_product'   => 'nullable',
            'variant_wise_stock'      => 'nullable',
            'image_aspect_ratio'      => 'nullable',
            'carousel_card_row'       => 'nullable',
            'position_wise_product'   => 'nullable',
            'template_id'             => 'nullable',
            'steadfast_base_url'      => 'nullable',
            'show_fraud_checker'      => 'nullable',
            'amarpay_active'          => 'nullable',
            'ssl_active'              => 'nullable',
            'customer_rec_in_table'   => 'nullable',
            'lang'                    => 'nullable',
            'multivendor_active'      => 'nullable',
            'active_develop_by'       => 'nullable',
            'sms_on'                  => 'nullable',
            'bkash_active'            => 'nullable',
            'incomplete_order_system' => 'nullable',
            'active_assign_order_system' => 'nullable',
            'affiliate_active'        => 'nullable',
            'show_merchant_panel'     => 'nullable',
            'browser_side_with'       => 'nullable',
            'active_server_side'      => 'nullable',
            'fb_access_token'         => 'nullable',
            'fb_pixel_id'             => 'nullable',
            'fb_api_version'          => 'nullable',
            'test_event_code'         => 'nullable',
            'pathao_base_url'         => 'nullable|string',
            'redx_base_url'           => 'nullable|string',
            'coupon'                  => 'nullable',
        ]);


        if ($request->has('variant_wise_stock')) {
            $variantWiseStock   = (int) $request->variant_wise_stock;
            $variantStockActive = (int) $request->variant_stock_active;

            if ($variantWiseStock === 0) {
                $validatedData['variant_stock_active'] = 0;
            }

            if ($variantWiseStock === 1 && $variantStockActive === 1) {
                $validatedData['variant_stock_active'] = 1;
            }
        }

        $setting = SiteConfiguration::first();

        if ($setting) {
            $setting->update($validatedData);
        } else {
            SiteConfiguration::create($validatedData);
        };

        return response()->json([
            'status' => 'SUCCESS',
            'message' => 'Site Info updated successfully',
        ]);
    }

    public function edit_site_info(Request $request, $id)
    {
        // return $request;
        $request->validate([
            'title'                 => 'required',
            'header_contact_number' => 'required',
            'meta_title'            => 'nullable|max:70',
            'meta_content'          => 'nullable|max:250',
        ]);

        $setting = GeneralSetting::findOrFail($id);
        $setting->title                         =   $request->title;
        $setting->reseller_refer_commission     =   $request->reseller_refer_commission;
        $setting->facebook_pixel                =   $request->facebook_pixel;
        $setting->facebook_chat_plugin          =   $request->facebook_chat_plugin;
        $setting->facebook_domain_verification  =   $request->facebook_domain_verification;
        $setting->google_analytics              =   $request->google_analytics;
        $setting->google_domain_verification    =   $request->google_domain_verification;
        $setting->google_body_tag               =   $request->google_body_tag;
        $setting->header_contact_number         =   $request->header_contact_number;
        $setting->header_contact_number_two     =   $request->header_contact_number_two;
        $setting->header_contact_number_three   =   $request->header_contact_number_three;
        // $setting->header_contact_number_four   =   $request->header_contact_number_four;
        $setting->invoice_address_details       =   $request->invoice_address_details;
        $setting->sms_api_username              =   $request->sms_api_username;
        $setting->sms_api_password              =   $request->sms_api_password;
        $setting->sms_api_sender_id             =   $request->sms_api_sender_id ;
        $setting->whatsapp_number               =   $request->whatsapp_number;
        $setting->select_area                   =   $request->select_area;
        $setting->city_sub_city                 =   $request->city_sub_city ;
        $setting->meta_title                    =   $request->meta_title;
        $setting->meta_description              =   $request->meta_description ;
        $setting->meta_key                      =   $request->meta_key ;
        $setting->meta_content                  =   $request->meta_content ;
        $setting->google_client_id              =   $request->google_client_id ;
        $setting->google_client_secret          =   $request->google_client_secret;
        $setting->google_redirect               =   $request->google_redirect ;
        $setting->facebook_app_id               =   $request->facebook_app_id ;
        $setting->facebook_app_secret           =   $request->facebook_app_secret ;
        $setting->facebook_redirect             =   $request->facebook_redirect;
        $setting->header_email                  =   $request->header_email ;
        $setting->font_url                      =   $request->font_url ;
        $setting->font_family                   =   $request->font_family;
        

        if ($request->hasFile('logo')) {
            $logo_path = $request->file('logo')->store('images/general_setting', 'public');
            $setting->logo = $logo_path;
        }

        if ($request->hasFile('icon')) {
            $icon_path = $request->file('icon')->store('images/general_setting', 'public');
            $setting->icon = $icon_path;
        }

        if ($setting->save()) {
            return response()->json([
                'status' => 'SUCCESS',
                'message' => 'Site Info updated successfully',
            ]);
        }
    }



    public function getSiteSetup()
    {

        $setting = SiteConfiguration::first();
        if ($setting) {
            return response()->json([
                "status" => true,
                "setting" => $setting,
            ]);
        }
    }


    public function updateSiteSetup(Request $request)
    {

        $validatedData = $request->validate([
            'show_city_sub_city' => 'nullable',
            'show_stock_out'     => 'nullable',
            'card_row'           => 'nullable',
            'show_checkout_note' => 'nullable',
        ]);

        $setting = SiteConfiguration::first();
        if ($setting) {
            $setting->update($validatedData);
        } else {
            SiteConfiguration::create($validatedData);
        };

        return response()->json([
            'status' => true,
            'message' => 'Site Info updated successfully',
        ]);
    }



    public function templates()
    {
        $templates = Template::all();
        return sendResponseWithData('templates', $templates, true);
    }



    public function editTemplates($id)
    {
        $template = Template::find($id);
        return sendResponseWithData('template', $template, true);
    }



    public function updateTemplates(Request $request, $id)
    {
        $template = Template::find($id);
        $template->name = $request->name;
        if ($request->hasFile('preview_image')) {
            $path = $request->file('preview_image')->store('images/template_image', 'public');
            $template->preview_image = $path;
        }
        $template->save();
        return sendResponseWithMessage(true, 'Update Done');
    }
    public function verifyFacebookPixel(Request $request, FacebookConversionService $facebook)
    {
        $pixelId = $request->input('pixel_id');
        $accessToken = $request->input('access_token');

        if (empty($pixelId) || empty($accessToken)) {
            return response()->json([
                'status' => false,
                'message' => 'Pixel ID and Access Token are required'
            ], 422);
        }

        return $facebook->verify($pixelId, $accessToken);
    }



    public function exportDB()
    {
        $dbHost = env('DB_HOST', '127.0.0.1');
        $dbName = env('DB_DATABASE', 'seo_friendly_new_db_2.0');
        $dbUser = env('DB_USERNAME', 'root');
        $dbPass = env('DB_PASSWORD', '');

        $timestamp = Carbon::now()->format('Y-m-d_H-i-s');
        $fileName = "backup_{$timestamp}.sql";

        $command = "mysqldump --host={$dbHost} --user={$dbUser} --password={$dbPass} {$dbName}";

        return response()->streamDownload(function () use ($command) {
            $process = popen($command, 'r');
            fpassthru($process);
            pclose($process);
        }, $fileName, [
            "Content-Type" => "application/octet-stream",
            "Content-Disposition" => "attachment; filename=\"$fileName\""
        ]);
    }
}
