<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\LetterHead;
use App\Models\VoucherType;
use App\Models\Company;
use App\Models\FontFamily;

class LetterHeadsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $letter_heads = LetterHead::select(
            'letter_heads.id',
            'letter_heads.title',
            'letter_heads.full_image as full_image',
            'letter_heads.image_url as image_url',
            'letter_heads.image_style as image_style',
            'letter_heads.title_style as title_style',
            'letter_heads.sub_title_style as sub_title_style',
            'letter_heads.content_alignment as content_alignment',
            'letter_heads.logo_position as logo_position',
            'letter_heads.company_id as company_id',
            'letter_heads.status as status',
            'letter_heads.custom_logo_url',
            'letter_heads.hide_logo',
            'letter_heads.custom_logo_status',
            'letter_heads.is_default as is_default',
            'companies.name as company_name',
            'voucher_types.name as voucher_type_code'
        )->leftJoin('companies' , 'companies.id' , '=' , 'letter_heads.company_id')
        ->leftJoin('voucher_types' , 'voucher_types.id' , '=' , 'letter_heads.voucher_type_code')
        ->orderBy('letter_heads.voucher_type_code', 'ASC');

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $letter_heads = $letter_heads->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('letter_heads.voucher_type_code', 'like', '%'.$search_query.'%')
                ->orWhere('letter_heads.content_alignment', 'like', '%'.$search_query.'%')
                ->orWhere('letter_heads.logo_position', 'like', '%'.$search_query.'%')
                ->orWhere('companies.name', 'like', '%'.$search_query.'%');
            })->paginate($sort_by);

            return view('letter-heads.table', compact('letter_heads'));
        } else {
            $letter_heads = $letter_heads->paginate(10);

            return view('letter-heads.index', compact('letter_heads'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request,$id='')
    {
        $letter_heads = LetterHead::select(
            'letter_heads.id',
            'letter_heads.voucher_type_code as voucher_type_code',
            'letter_heads.full_image as full_image',
            'letter_heads.image_url as image_url',
            'letter_heads.image_style as image_style',
            'letter_heads.title_style as title_style',
            'letter_heads.sub_title_style as sub_title_style',
            'letter_heads.content_alignment as content_alignment',
            'letter_heads.logo_position as logo_position',
            'letter_heads.company_id as company_id',
            'letter_heads.status as status',
            'letter_heads.is_default as is_default',
            'companies.name as company_name',
        )->leftJoin('companies' , 'companies.id' , '=' , 'letter_heads.company_id')
        ->get();

        $voucher_types = VoucherType::all();
        $companies     = Company::all();
        $fonts         = FontFamily::get();

        return view('letter-heads.create', compact('letter_heads' , 'voucher_types' , 'companies' , 'fonts'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {

        $letter_heads  = LetterHead::find($id);

        // Decode JSON fields only if they are still in string format
        $letter_heads->image_style     = is_string($letter_heads->image_style) ? json_decode($letter_heads->image_style, true) : $letter_heads->image_style;
        $letter_heads->title_style     = is_string($letter_heads->title_style) ? json_decode($letter_heads->title_style, true) : $letter_heads->title_style;
        $letter_heads->sub_title_style = is_string($letter_heads->sub_title_style) ? json_decode($letter_heads->sub_title_style, true) : $letter_heads->sub_title_style;


        $voucher_types = VoucherType::all();
        $companies     = Company::all();
        $fonts         = FontFamily::get();

        return view('letter-heads.edit', compact('letter_heads', 'voucher_types', 'companies', 'fonts'));
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $letter_heads = LetterHead::findOrFail($id);
        $letter_heads->delete();

        return response()->json([
            'success' => true,
            'message' => 'Letter Head Deleted successfully',
            'data'    => [
                'redirect' => '', 
            ]
        ]);
    }

    public function storeLetterHeads(Request $request)
    {
        $validator = \Validator::make($request->all(), [

            //Normal Columns
            'title'              => 'required',
            // 'voucher_type_code'  => 'required',
            'content_alignment'  => 'required',
            'logo_position'      => 'required',
            'company_id'         => 'required',
            'custom_logo_status' => 'nullable',

            // Title
            'title_font_color'       => 'required',
            'title_background_color' => 'required',
            'title_text_decoration'  => 'required',
            'title_font_family'      => 'required',
            'title_font_size'        => 'required',
            'title_font_style'       => 'required',
            'title_font_weight'      => 'required',
            'title_font_padding'     => 'required',

            // Sub Title
            'sub_title_font_color'       => 'required',
            'sub_title_background_color' => 'required',
            'sub_title_text_decoration'  => 'required',
            'sub_title_font_family'      => 'required',
            'sub_title_font_size'        => 'required',
            'sub_title_font_style'       => 'required',
            'sub_title_font_weight'      => 'required',
            'sub_title_font_padding'     => 'required',

            // Image
            'image_height'    => 'required',
            'image_width'     => 'required',
            'image_margin'    => 'required',
            'image_padding'   => 'required',
            'image_url'       => 'nullable|file', 
            'custom_logo_url' => 'nullable|file', 
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->getMessageBag()->first(),
                'data'    => [],
            ]);
        }

        $data = $request->all(); 
        $status = $request->has('custom_logo_status') ? 1 : 0;

        if ($request->hasFile('custom_logo_url')) {
            $path     = 'uploads/letter-heads/custom-logos';
            $response = uploadImage($path,$request->custom_logo_url);

            if ($response['status'] == true) {
                $data['custom_logo_url'] = $response['file_name'];
            }
        }

        if ($request->hasFile('image_url')) {
            $destinationPath = 'uploads/letter-heads/full-width-image';
            $response        = uploadImage($path,$request->image_url);

            if ($response['status'] == true) {
                $data['image_url'] = $response['file_name'];
            }
        }

        $letter_heads = LetterHead::create([
            'title'              => $data['title'],
            'voucher_type_code'  => $data['voucher_type_code'],
            'content_alignment'  => $data['content_alignment'],
            'logo_position'      => $data['logo_position'],
            'company_id'         => $data['company_id'],
            'custom_logo_url'    => $data['custom_logo_url'] ?? null,
            'image_url'          => $data['image_url'] ?? null,      
            'custom_logo_status' => $status,   

            'image_style' => json_encode([
                'image_height'  => $data['image_height'],
                'image_width'   => $data['image_width'],
                'image_margin'  => $data['image_margin'],
                'image_padding' => $data['image_padding'],
            ]),

            'title_style' => json_encode([
                'title_font_color'       => $data['title_font_color'],
                'title_background_color' => $data['title_background_color'],
                'title_text_decoration'  => $data['title_text_decoration'],
                'title_font_family'      => $data['title_font_family'],
                'title_font_size'        => $data['title_font_size'],
                'title_font_style'       => $data['title_font_style'],
                'title_font_weight'      => $data['title_font_weight'],
                'title_font_padding'     => $data['title_font_padding'],
            ]),

            'sub_title_style' => json_encode([
                'sub_title_font_color'       => $data['sub_title_font_color'],
                'sub_title_background_color' => $data['sub_title_background_color'],
                'sub_title_text_decoration'  => $data['sub_title_text_decoration'],
                'sub_title_font_family'      => $data['sub_title_font_family'],
                'sub_title_font_size'        => $data['sub_title_font_size'],
                'sub_title_font_style'       => $data['sub_title_font_style'],
                'sub_title_font_weight'      => $data['sub_title_font_weight'],
                'sub_title_font_padding'     => $data['sub_title_font_padding'],
            ]),
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Letter Head Created successfully',
            'data'    => [],
        ]);
    }

    public function updateLetterHeads(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'title'                      => 'required',
            // 'voucher_type_code'          => 'required',
            'content_alignment'          => 'required',
            'logo_position'              => 'required',
            'company_id'                 => 'required',
            'title_font_color'           => 'required',
            'title_background_color'     => 'required',
            'title_text_decoration'      => 'required',
            'title_font_family'          => 'required',
            'title_font_size'            => 'required',
            'title_font_style'           => 'required',
            'title_font_weight'          => 'required',
            'title_font_padding'         => 'required',
            'sub_title_font_color'       => 'required',
            'sub_title_background_color' => 'required',
            'sub_title_text_decoration'  => 'required',
            'sub_title_font_family'      => 'required',
            'sub_title_font_size'        => 'required',
            'sub_title_font_style'       => 'required',
            'sub_title_font_weight'      => 'required',
            'sub_title_font_padding'     => 'required',
            'image_height'               => 'required',
            'image_width'                => 'required',
            'image_margin'               => 'required',
            'image_padding'              => 'required',
            'image_url'                  => 'nullable',
            'custom_logo_url'            => 'nullable',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->getMessageBag()->first(),
                'data'    => [
                    'redirect' => '',
                ],
            ]);
        }

        $data = [
            'title'             => $request->title,
            'voucher_type_code' => $request->voucher_type_code,
            'content_alignment' => $request->content_alignment,
            'logo_position'     => $request->logo_position,
            'company_id'        => $request->company_id,

            'image_style' => json_encode([
                'image_height'    => $request->image_height,
                'image_width'     => $request->image_width,
                'image_margin'    => $request->image_margin,
                'image_padding'   => $request->image_padding,
            ]),

            'title_style' => json_encode([
                'title_font_color'       => $request->title_font_color,
                'title_background_color' => $request->title_background_color,
                'title_text_decoration'  => $request->title_text_decoration,
                'title_font_family'      => $request->title_font_family,
                'title_font_size'        => $request->title_font_size,
                'title_font_style'       => $request->title_font_style,
                'title_font_weight'      => $request->title_font_weight,
                'title_font_padding'     => $request->title_font_padding,
            ]),

            'sub_title_style' => json_encode([
                'sub_title_font_color'       => $request->sub_title_font_color,
                'sub_title_background_color' => $request->sub_title_background_color,
                'sub_title_text_decoration'  => $request->sub_title_text_decoration,
                'sub_title_font_family'      => $request->sub_title_font_family,
                'sub_title_font_size'        => $request->sub_title_font_size,
                'sub_title_font_style'       => $request->sub_title_font_style,
                'sub_title_font_weight'      => $request->sub_title_font_weight,
                'sub_title_font_padding'     => $request->sub_title_font_padding,
            ]),
        ];
        $data['custom_logo_status'] = $request->has('custom_logo_status') ? 1 : 0;

        $letter_heads = LetterHead::findOrFail($id);

        if ($request->hasFile('custom_logo_url')) {
            $destinationPath = 'uploads/letter-heads/custom-logos';
            $response        = uploadImage($destinationPath,$request->custom_logo_url, $letter_heads->custom_logo_url);

            if ($response['status'] == true) {
                $data['custom_logo_url'] = $response['file_name'];
            } 
        }

        if ($request->hasFile('image_url')) {
            $destinationPath = 'uploads/letter-heads/full-width-image';
            $response        = uploadImage($destinationPath,$request->image_url, $letter_heads->image_url);

            if ($response['status'] == true) {
                $data['image_url'] = $response['file_name'];
            }
        }

        $letter_heads->update($data);

        return response()->json([
            'success' => true,
            'message' => 'Letter Head updated successfully',
            'data'    => [
            ],
        ]);
    }

    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status );
            $update = LetterHead::where('id', '=', $request->id)->update($data);

            if($update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Letter Head status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }

    public function changeStatusIsdefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_default' => $request->status );
            $update = LetterHead::where('id', '=', $request->id)->update($data);


            if($update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Letter Head is Default status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    } 

    public function changeStatusfullImage(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('full_image' => $request->status );
            $update = LetterHead::where('id', '=', $request->id)->update($data);

            if($update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Letter Head Full Image successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }

    public function changeStatusShowLogo(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('hide_logo' => $request->status );
            $update = LetterHead::where('id', '=', $request->id)->update($data);

            if($update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Letter Head Hide Image Status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }

}