<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\BrandProduct;
use App\Models\CareerModel;
use App\Models\CategoryModel;
use App\Models\EnquiryCatalogModel;
use App\Models\EnquiryModel;
use App\Models\IndustryProduct;
use App\Models\PagesModel;
use App\Models\ProductAttributeModel;
use App\Models\ProductBrandModel;
use App\Models\ProductIndustryModel;
use App\Models\ProductModel;
use App\Models\SizeModel;
use App\Models\SizeProduct;
use App\Models\SliderModel;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;

class FrontendController extends Controller
{

    public function index(Request $request)
    {
        $slidersData = SliderModel::Where('status', 1)->get();
        return view('index', compact('slidersData'));
        // return view('maintain');
    }

    public function contact()
    {
        return view('contact');
    }

    public function products()
    {
        $productType  = CategoryModel::Where('status', 1)->get();
        $brandData    = ProductBrandModel::Where('status', 1)->get();
        $industryData = ProductIndustryModel::Where('status', 1)->get();
        return view('products', compact('productType', 'brandData', 'industryData'));
    }

    public function getProduct($name = '')
    {

        $product = ProductModel::Where('product_slug', $name)->first();
        $id      = isset($product->id) ? $product->id : 0;

        if ($id != '') {
            $record = ProductModel::with('category')->Where('id', $id)->first();

            $brands = BrandProduct::from('product_brand as pb')
                ->leftJoin('brand as b', 'b.id', '=', 'pb.brand_id')
                ->where('pb.product_id', $id)
                ->select('b.brand', 'b.id')
                ->get();
            $industrys = IndustryProduct::from('product_industry as pb')
                ->leftJoin('industry as b', 'b.id', '=', 'pb.industry_id')
                ->where('pb.product_id', $id)
                ->select('b.industry', 'b.id')
                ->get();
            $size = SizeProduct::from('product_size as pb')
                ->leftJoin('size as b', 'b.id', '=', 'pb.size_id')
                ->where('pb.product_id', $id)
                ->select('b.size', 'b.id')
                ->get();

            $productItems = ProductAttributeModel::Where('product_id', $id)->get();

            return view('product_detail', compact('record', 'size', 'industrys', 'brands', 'productItems'));
        }

        //    $records = ProductModel::get();
        //    foreach($records as $row)
        //    {
        //      ProductModel::Where('id',$row->id)->update(array('product_slug'=>Str::slug($row->product_name)));
        //    }

    }

    public function submitEnquiry(Request $request)
    {
        $input = $request->all();

        $name     = isset($input['name']) ? $input['name'] : '';
        $email    = isset($input['email']) ? $input['email'] : '';
        $phone    = isset($input['phone']) ? $input['phone'] : '';
        $brand    = isset($input['brand']) ? $input['brand'] : '';
        $size     = isset($input['size']) ? $input['size'] : '';
        $industry = isset($input['industry']) ? $input['industry'] : '';

        if ($brand != '') {
            $bname = ProductBrandModel::Where('id', $brand)->value('brand');
        }
        if ($size != '') {
            $sname = SizeModel::Where('id', $size)->value('size');
        }
        if ($industry != '') {
            $iname = ProductIndustryModel::Where('id', $industry)->value('industry');
        }

        $data = [
            'name'     => $name,
            'email'    => $email,
            'phone'    => $phone,
            'brand'    => $bname ?? '',
            'size'     => $sname ?? '',
            'industry' => $iname ?? '',
            'ip'       => $request->ip(),
        ];
        try {

            Mail::send('email.enquiry', ['data' => $data], function ($message) use ($data) {
                $message->from('enquiry@palaniappaelectronics.in', 'Palaniappa Electronics');
                $message->to('hussain@alphasoftz.in')
                    ->subject('New Enquiry from Website');
                // ->replyTo($data['email']);
            });
            EnquiryModel::create($data);
            return response()->json(['status' => 1]);
        } catch (Exception $e) {
            return response()->json(['status' => 0]);
        }
    }

    public function download($token)
    {
        $id = EnquiryCatalogModel::Where('hash', $token)->value('id');
        if ($id != '') {
            $path = public_path('assets/catalog/catalog.pdf');
            return response()->download($path);
        } else {
            return redirect()->back()->with('error', 'Token mismatching');
        }
    }

    public function downloadCatalog(Request $request)
    {
        $input = $request->all();
        $phone = isset($input['phone']) ? $input['phone'] : '';
        $token = hash('sha256', Str::random(20));
        $data  = [
            'mobile' => $phone,
            'ip'     => $request->ip(),
            'hash'   => $token,
        ];
        $insert = EnquiryCatalogModel::create($data);
        $html   = '<a href="' . route('download', ['token' => $token]) . '">Click here to Download</a>';
        if ($insert['id'] > 0) {
            return response()->json(['status' => 1, 'link' => $html]);
        }
    }

    public function sendSms()
    {
        $payload = [
            "sender"         => "Myshop",
            "recipient"      => "9894764234",
            "content"        => "Your  Id is KCT00012",
            "type"           => "marketing",
            "unicodeEnabled" => true,
        ];

        $ch = curl_init("https://api.brevo.com/v3/transactionalSMS/send");

        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "accept: application/json",
            "content-type: application/json",
            "api-key: " . env('BREVO_API_KEY'),
        ]);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }

    public function sendCareer(Request $request)
    {
        $request->validate([
            'name'    => 'required|string|max:255',
            'email'   => 'required',
            'message' => 'required|string|max:2000',
            'file'    => 'required|mimes:pdf|max:2048',
        ]);

        $contact = $request->email;

        if (
            ! filter_var($contact, FILTER_VALIDATE_EMAIL) &&
            ! preg_match('/^[0-9]{10}$/', $contact)
        ) {
            return back()->withErrors([
                'contact' => 'Please enter a valid email address or 10-digit mobile number.',
            ])->withInput();
        }

        $data            = [];
        $data['name']    = $request->name;
        $data['message'] = $request->message;
        $data['ip_address']  = $request->ip();

        // Separate email & mobile
        if (is_numeric($request->email)) {
            $data['mobile'] = $request->email;
            $data['email']  = null;
        } else {
            $data['email']  = $request->email;
            $data['mobile'] = null;
        }


        if ($request->hasFile('file') != '') {
            $file     = $request->file('file');
            $front = 'career' . time() . '_' . str_replace(' ', '_', $file->getClientOriginalName());
            $file->move(public_path('/uploads/career/'), $front);
            $fronturl           = URL::to('/') . '/uploads/career/' . $front;
            $data['resume'] = $fronturl;
        }

        $insert = CareerModel::create($data);


        if ($insert['id'] > 0) {
            return back()->with('success', 'Data saved successfully');
        } else {
            return back()->with('error', 'something went wrong');
        }
    }

    public function sendMail(Request $request)
    {
        $input = $request->all();
        $name     = isset($input['name']) ? $input['name'] : '';
        $email    = isset($input['email']) ? $input['email'] : '';
        $phone    = isset($input['phone']) ? $input['phone'] : '';
        $subject    = isset($input['subject']) ? $input['subject'] : '';
        $message    = isset($input['message']) ? $input['message'] : '';
        $request->validate([
            'name' => [
                'required',
                'string',
                'max:255',
                'regex:/^[a-zA-Z\s]+$/'
            ],

            'email' => [
                'required',
                'email:rfc,dns',
                'max:255'
            ],

            'subject' => [
                'required',
                'string',
                'max:255'
            ],

            'message' => [
                'required',
                'string',
                'max:2000'
            ],
        ]);

        $data = [
            'name'     => $name,
            'email'    => $email,
            'phone'    => $phone,
            'message'    => $message,
            'subject'    => $subject ?? '',
        ];
        try {

            Mail::send('email.contact', ['data' => $data], function ($message) use ($data) {
                $message->from('enquiry@palaniappaelectronics.in', 'Palaniappa Electronics');
                $message->to('hussain@alphasoftz.in')
                    ->subject('New Enquiry from Website Contact Form');
                // ->replyTo($data['email']);
            });
           return back()->with('success', 'Your message has been sent. Thank you!');
        } catch (Exception $e) {
            return back()->with('success', 'something went wrong');
        }
    }

    public function getAjaxProducts(Request $request)
    {
        $offset        = $request->get('offset', 0);
        $limit         = $request->get('limit', 12);
        $categoryId    = $request->get('category');
        $brandId       = $request->get('brand');
        $industryId    = $request->get('industry');
        $category_slug = $request->get('category_slug');

        DB::enableQueryLog();
        $products = ProductModel::query()->from('products as p')
            ->leftJoin('product_attributes as pi', 'pi.product_id', '=', 'p.id')
            ->select(['p.id', 'p.product_name', 'pi.product_image']);
        // 🔹 Filter: Category
        if ($categoryId) {
            $products->where('p.category_id', $categoryId);
        }

        if ($category_slug != '') {
            $cate   = str_replace("-", " ", $category_slug);
            $cateId = CategoryModel::Where('category_name', $cate)->value('id');
            if ($cateId != '') {
                $products->where('p.category_id', $cateId);
            }
        }

        // Brand filter (pivot)
        if ($brandId) {
            $products->whereExists(function ($q) use ($brandId) {
                $q->select(DB::raw(1))
                    ->from('product_brand as pb')
                    ->whereColumn('pb.product_id', 'p.id')
                    ->where('pb.brand_id', $brandId);
            });
        }

        // Industry filter (pivot)
        if ($industryId) {
            $products->whereExists(function ($q) use ($industryId) {
                $q->select(DB::raw(1))
                    ->from('product_industry as pi2')
                    ->whereColumn('pi2.product_id', 'p.id')
                    ->where('pi2.industry_id', $industryId);
            });
        }

        $records = $products->offset($offset)
            ->limit($limit)->get();
        // $d = DB::getRawQueryLog();
        //dd($d);
        return view('ajax_products', compact('records', 'offset', 'limit'));
    }

    public function career()
    {
        return view('career');
    }

    public function privacy_policy()
    {
        $record = PagesModel::Where('type', 1)->first();
        $type   = 1;
        return view('pages', compact('record', 'type'));
    }

    public function terms_condition()
    {
        $record = PagesModel::Where('type', 2)->first();
        $type   = 2;
        return view('pages', compact('record', 'type'));
    }

    public function about()
    {
        return view('about');
    }

    public function vendor()
    {
        return view('vendor');
    }
}
