<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Http\Controllers\Helpers\FileHelperController;
use App\Http\Models\ArticleModel;
use App\Http\Models\SubCategoryModel;
use DateTime;
use Redirect;
use Validator;
use View;
use File;
use Image;

class ArticleController extends Controller
{
    private $fileHelper;

    public function __construct(
        FileHelperController  $fileHelperAccess
    ) {
        // Data accessor
        $this->fileHelper = $fileHelperAccess;
    }

    public function index($subId = null, $fromDate = null, $toDate = null)
    {
        $fromDateFormatted = $fromDate ? date('Y-m-d', strtotime($fromDate)) . ' 00:00:00' : null;
        $toDateFormatted = $toDate ? date('Y-m-d', strtotime($toDate)) . ' 23:59:59' : null;

        $query = ArticleModel::where('active', 1);

         if ($subId != null) {
            $query->whereRaw('FIND_IN_SET(?, sub_category_ids)', [$subId]);
        }

        if ($fromDate || $toDate) {
            $dateConditions = [];
            if ($fromDate) {
                $dateConditions[] = ['article.due_date', '>=', $fromDateFormatted];
            }
            if ($toDate) {
                $dateConditions[] = ['article.due_date', '<=', $toDateFormatted];
            }
            $query->where($dateConditions);
        }
            

        // Execute the query and get the results
        $data = $query
            ->where('category_id', 1)
            ->orderBy('id', 'DESC')
            ->get();

        return View::make("backend/article/index")
            ->with('itemView', $data)
            ->with('fromDateView', $fromDate)
            ->with('toDateView', $toDate);
    }

    public function add()
    {
        $subCategories = SubCategoryModel::where('category_id', 1)->where('active', 1)->get();
        return View::make("backend/article/add")
            ->with('subCategoriesView', $subCategories);
    }

    public function insert(Request $request)
    {
        // keep data en
        $avatar = $request->file('avatar');
        $sub_categories = $request->input('sub_categories');
        $due_date = $request->input('due_date');
        $name = $request->input('name');
        $name_en = $request->input('name_en');
        $description = $request->input('description');
        $description_en = $request->input('description_en');

        // validate
        $validator = Validator::make($request->all(), [
            'sub_categories' => 'required',
            'due_date' => 'required',
            'name' => 'required',
            'name_en' => 'required',
            'description' => 'required',
            'description_en' => 'required',
        ]);

        if ($validator->fails()) {
            return Redirect::to("no-where-else/add-article")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", "Data can't empty");
        }

        if (empty($avatar)) {
            return Redirect::to("no-where-else/add-article")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", "Please choose picture");
        }
        // check file
        if (!empty($avatar)) {
            $isFileTooLarge = $this->fileHelper->checkFileSize5MB($avatar->getSize());
            if ($isFileTooLarge) {
                return Redirect::to("no-where-else/add-article")
                    ->withInput()
                    ->with("messageFail", "Fail")
                    ->with("messageDetail", 'File too large, file less then 10MB');
            }
        }

        $dateObject = DateTime::createFromFormat('d-m-Y', $due_date);
        $formattedDate = $dateObject->format('Y-m-d'); // Convert to YYYY-MM-DD


        // prepared data
        $data = [
            'category_id' => 1,
            'sub_category_ids' => implode(", ", $sub_categories),
            'due_date' => $formattedDate,
            'name' => $name,
            'name_en' => $name_en,
            'description' => $description,
            'description_en' => $description_en,
            'created_at' => new DateTime(),
            'updated_at' => new DateTime(),
        ];

        // insert to database
        $result =  ArticleModel::insertGetId($data);
        if ($result > 0) { // insert success then return ID

            // Image
            if (!empty($avatar)) {
                $this->uploadImageAvatar($request, $result);
            }

            // redirect with message
            return Redirect::to("no-where-else/article")
                ->with("messageSuccess", "Success")
                ->with("messageDetail", 'Added success');
        } else { // insert fail
            return Redirect::to("no-where-else/add-article")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Added category fail');
        }
    }

    public function edit($id)
    {
        // get by id
        $data = ArticleModel::where('id', $id)->first();
        if (is_null($data)) { // not found
            return Redirect::to("no-where-else/article")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Not found data');
        }

        $sub_categories = SubCategoryModel::where('category_id', 1)->where('active', 1)->get();
        return View::make('backend/article/edit')
            ->with('idView', $id)
            ->with('itemView', $data)
            ->with('subCategoriesView', $sub_categories);
    }

    public function update(Request $request)
    {
        // keep data en
        $id = $request->input('id');
        $sub_categories = $request->input('sub_categories');
        $due_date = $request->input('due_date');
        $name = $request->input('name');
        $name_en = $request->input('name_en');
        $description = $request->input('description');
        $description_en = $request->input('description_en');

        $active = $request->input('active');

        $avatar = $request->file('avatar');
        $imgReq = $avatar ? 'required|image|mimes:jpeg,png,jpg|max:10240' : '';

        // validate
        $validator = Validator::make($request->all(), [
            'sub_categories' => 'required',
            'due_date' => 'required',
            'name' => 'required',
            'name_en' => 'required',
            'description' => 'required',
            'description_en' => 'required',
            'avatar' => $imgReq
        ]);

        if ($validator->fails()) {
            return Redirect::to("no-where-else/edit-article/" . $id)
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Data cannot be empty');
        }


        $dateObject = DateTime::createFromFormat('d-m-Y', $due_date);
        $formattedDate = $dateObject->format('Y-m-d'); // Convert to YYYY-MM-DD
        $data = [
            'category_id' => 1,
            'sub_category_ids' => implode(", ", $sub_categories),
            'due_date' => $formattedDate,
            'active' => $active,
            'name' => $name,
            'name_en' => $name_en,
            'description' => $description,
            'description_en' => $description_en,
            'active' => $active,
            'updated_at' => new DateTime(),
        ];

        // update to database
        ArticleModel::where('id', $id)
            ->update($data);

        if (!empty($avatar)) {
            $this->uploadImageAvatar($request, $id);
        }

        // redirect with message
        return Redirect::to("no-where-else/article")
            ->withInput()
            ->with("messageSuccess", "Success")
            ->with("messageDetail", 'Updated success');
    }

    public function delete(Request $request)
    {
        $id = $request->input('item_id');
        ArticleModel::where('id', '=', $id)->delete();
        return response()->json([
            'status' => true,
            'message' => "Deleted success"
        ]);
    }

    public function uploadImageAvatar($request, $id)
    {
        // local path
        $localPath = '/uploads/article/' . $id;

        // request
        $image = $request->file('avatar');

        // rename
        $imgName = time() . '.' . $image->extension();

        // destination
        $destinationUrl = url($localPath);
        $destinationPath = public_path($localPath);

        // create folder
        if (File::isDirectory($destinationPath . '/original') == false) {
            File::makeDirectory($destinationPath . '/original', 0777, true);
        }
        if (File::isDirectory($destinationPath . '/thumbnail') == false) {
            File::makeDirectory($destinationPath . '/thumbnail', 0777, true);
        }

        // call lib
        $img = Image::make($image->path());

        // save original
        $img->save($destinationPath . '/original/' . $imgName);

        // save thumbnail
        $img->resize(1200, 1200, function ($constraint) {
            $constraint->aspectRatio();
        })->save($destinationPath . '/thumbnail/' . $imgName);

        // update db
        $dataImage = [
            'image_url' => $destinationUrl,
            'image_name' => $imgName
        ];
        ArticleModel::where('id', $id)
            ->update($dataImage);
    }


    // Handle file or URL upload based on ImageTool configuration
    public function uploadImage(Request $request)
    {
        if ($request->hasFile('image')) {
            return $this->handleFileUpload($request);
        } elseif ($request->has('url')) {
            return $this->handleUrlUpload($request->input('url'));
        }

        return response()->json(['error' => 'No valid input provided'], 400);
    }

    // Handle file upload
    private function handleFileUpload($request)
    {
        $image = $request->file('image');
        $imgName = uniqid() . time() . '.' . $image->extension();
        $localPath = '/uploads/article/';
        
        $destinationUrl = url($localPath . $imgName);
        $destinationPath = public_path($localPath);

        // Ensure directory exists
        if (!File::isDirectory($destinationPath)) {
            File::makeDirectory($destinationPath, 0777, true);
        }

        // Save original image
        $img = Image::make($image->path());
        $img->save($destinationPath . $imgName);

        return response()->json([
            'success' => 1,
            'file' => [
                'url' => $destinationUrl
            ]
        ]);
    }

    // Handle image upload by URL
    private function handleUrlUpload($url)
    {
        $imgName = uniqid() . time() . '.jpg';
        $localPath = '/uploads/article/';
        $destinationUrl = url($localPath . $imgName);
        $destinationPath = public_path($localPath);

        // Ensure directory exists
        if (!File::isDirectory($destinationPath)) {
            File::makeDirectory($destinationPath, 0777, true);
        }

        // Download image from the provided URL
        $img = Image::make($url);
        $img->save($destinationPath . $imgName);

        return response()->json([
            'success' => 1,
            'file' => [
                'url' => $destinationUrl
            ]
        ]);
    }
}
