<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Language;
use App\Models\PollQuestion;
use App\Models\Post;
use App\Models\Role;
use App\Models\Rss;
use App\Models\Subscriber;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use InvalidArgumentException;

class DashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:admin');
    }
    
    public function index(){
        $default_language = Language::where('is_default',1)->first();
        $data['total_post'] = Post::all()->count();
        $data['author_post'] = Auth::guard('admin')->user()->posts->count();
        $data['pending_posts'] = Post::all()->where('is_pending','=',1)->where('status','=','true')->count();
        $data['author_pending'] = Auth::guard('admin')->user()->posts()->where('is_pending','=',1)->where('status','=','true')->count();
        $data['drafts'] = Auth::guard('admin')->user()->posts()->where('status','=','draft')->count();
        $data['schedules'] = Auth::guard('admin')->user()->posts()->where('status','=','true')->where('schedule_post','=',1)->where('is_pending','=',0)->count();
        $data['rss'] = Rss::all()->count();
        $data['polls'] = PollQuestion::all()->count();
        $data['userRole'] = Role::where('id','!=',1)->get();
        $data['subscribers'] = Subscriber::orderBy('id','desc')->take(10)->get();
        $data['categories'] = Category::where('language_id','=',$default_language->id);

        // Premium dashboard data
        $data['recent_posts'] = Post::where('language_id', $default_language->id)->orderBy('id','desc')->take(8)->get();
        $data['today_posts'] = Post::whereDate('created_at', today())->count();
        $data['week_posts'] = Post::where('created_at','>=', now()->subDays(7))->count();
        $data['month_posts'] = Post::where('created_at','>=', now()->subDays(30))->count();
        $data['total_categories'] = Category::where('language_id','=',$default_language->id)->count();
        $data['approved_posts'] = Post::where('is_pending',0)->where('status','true')->count();

        // Monthly post trend (last 6 months)
        $monthly_labels = [];
        $monthly_counts = [];
        for ($i = 5; $i >= 0; $i--) {
            $date = now()->subMonths($i);
            $monthly_labels[] = $date->translatedFormat('M');
            $monthly_counts[] = Post::whereYear('created_at', $date->year)
                                    ->whereMonth('created_at', $date->month)->count();
        }
        $data['monthly_labels'] = json_encode($monthly_labels);
        $data['monthly_counts'] = json_encode($monthly_counts);

        // Category-wise post distribution (top 6 categories)
        $cat_data = Category::where('language_id','=',$default_language->id)
            ->withCount('posts')
            ->orderBy('posts_count','desc')
            ->take(6)->get();
        $data['cat_labels'] = json_encode($cat_data->pluck('title')->toArray());
        $data['cat_counts'] = json_encode($cat_data->pluck('posts_count')->toArray());

        return view('admin.dashboard',$data);
    }

    public function profile()
    {
        $data = Auth::guard('admin')->user();
        return view('admin.profile.edit',compact('data'));
    }

    public function profileupdate(Request $request)
    {
        //--- Validation Section
        $data = Auth::guard('admin')->user();
        $rules =
        [
            'photo' => 'mimes:jpeg,jpg,png,svg',
            'email' => 'required|unique:admins,email,'.$data->id,
        ];

        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
          return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
        }
        //--- Validation Section Ends
        $input = $request->all();
    
        if ($file = $request->file('photo'))
        {
            $name = time().$file->getClientOriginalName();
            $file->move('assets/images/admin/',$name);
            if($data->photo != null)
            {
                @unlink('assets/images/post/'.$data->image_big);
            }
            $input['photo'] = $name;
        }
        $data->update($input);
        $msg = 'Successfully updated your profile';
        return response()->json($msg);
    }

    public function passwordreset()
    {
        $data = Auth::guard('admin')->user();
        return view('admin.profile.password',compact('data'));
    }

    public function changepass(Request $request)
    {
        $admin = Auth::guard('admin')->user();
        if ($request->cpass){
            if (Hash::check($request->cpass, $admin->password)){
                if ($request->newpass == $request->renewpass){
                    $input['password'] = Hash::make($request->newpass);
                }else{
                    return response()->json(array('errors' => [ 0 => 'Confirm password does not match.' ]));
                }
            }else{
                return response()->json(array('errors' => [ 0 => 'Current password Does not match.' ]));
            }
        }
        $admin->update($input);
        $msg = 'Successfully change your passwprd';
        return response()->json($msg);
    }

    public function logout(){
        Auth::guard('admin')->logout();
        return redirect('/');
    }


    public function generate_bkup()
    {
        $bkuplink = "";
        $chk = file_get_contents('backup.txt');
        if ($chk != ""){
            $bkuplink = url($chk);
        }
        return view('admin.movetoserver',compact('bkuplink','chk'));
    }


    public function clear_bkup()
    {
        $destination  = public_path().'/install';
        $bkuplink = "";
        $chk = file_get_contents('backup.txt');
        if ($chk != ""){
            unlink(public_path($chk));
        }

        if (is_dir($destination)) {
            $this->deleteDir($destination);
        }
        $handle = fopen('backup.txt','w+');
        fwrite($handle,"");
        fclose($handle);
        //return "No Backup File Generated.";
        return redirect()->back()->with('success','Backup file Deleted Successfully!');
    }






    public function movescript(){
        ini_set('max_execution_time', 3000);

        $destination  = public_path().'/install';
        $chk = file_get_contents('backup.txt');
        if ($chk != ""){
            unlink(public_path($chk));
        }

        if (is_dir($destination)) {
            $this->deleteDir($destination);
        }

        $src = base_path().'/vendor/update';
        $this->recurse_copy($src,$destination);
        $files = public_path();
        $bkupname = 'GeniusCart-By-GeniusOcean-'.date('Y-m-d').'.zip';

        $zipper = new \Chumper\Zipper\Zipper;

        $zipper->make($bkupname)->add($files);

        $zipper->remove($bkupname);

        $zipper->close();

        $handle = fopen('backup.txt','w+');
        fwrite($handle,$bkupname);
        fclose($handle);

        if (is_dir($destination)) {
            $this->deleteDir($destination);
        }
        return response()->json(['status' => 'success','backupfile' => url($bkupname),'filename' => $bkupname],200);
    }

    public function recurse_copy($src,$dst) {
        $dir = opendir($src);
        @mkdir($dst);
        while(false !== ( $file = readdir($dir)) ) {
            if (( $file != '.' ) && ( $file != '..' )) {
                if ( is_dir($src . '/' . $file) ) {
                    $this->recurse_copy($src . '/' . $file,$dst . '/' . $file);
                }
                else {
                    copy($src . '/' . $file,$dst . '/' . $file);
                }
            }
        }
        closedir($dir);
    }

    public function deleteDir($dirPath) {
        if (! is_dir($dirPath)) {
            throw new InvalidArgumentException("$dirPath must be a directory");
        }
        if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
            $dirPath .= '/';
        }
        $files = glob($dirPath . '*', GLOB_MARK);
        foreach ($files as $file) {
            if (is_dir($file)) {
                self::deleteDir($file);
            } else {
                unlink($file);
            }
        }
        rmdir($dirPath);
    }

}
