<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Plan;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use DB;
use Auth;

class BillingController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    // public function __construct()
    // {
    //     $this->middleware('permission:view users')->only(['index', 'show']);
    //     $this->middleware('permission:create users')->only(['create', 'store']);
    //     $this->middleware('permission:edit users')->only(['edit', 'update']);
    //     $this->middleware('permission:delete users')->only(['destroy']);
    // }


    public function index()
    {
        $billings = Plan::orderBy('created_at', 'desc')->get();
        return view('admin.billings.list', compact('billings'));
    }

    public function create()
    {
        return view('admin.users.create', [
            'users' => Admin::all(),
            'roles' => Role::all()
        ]);
        
    }

   
    public function student_view(Request $request)
    {
        $id = base64_decode($request->id); // Assuming you're encoding the ID
    
        try {
            $student = User::findOrFail($id);
            return view('admin.students.view', compact('student'));
    
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Student not found.');
        }
    }

    public function billing_edit($id)
    {
        $billing = Plan::findOrFail(base64_decode($id));
        return view('admin.billings.edit', compact('billing'));
    }

   
    public function billing_update(Request $request)
    {
        $id = base64_decode($request->id);

        $rules = [
            'name'          => 'required',
            'interval'      => 'required',
            'price'         => 'required',
            // 'features_text' => 'required',
            // 'features_mark' => 'required',
            'features_text.*' => 'required|string',
            'features_mark.*' => 'required|in:0,1',
            
        ];

        $messages = [
            'name.required'           => 'Name is required.',
            'interval.required'       => 'Interval is required.',
            'price.required'          => 'Price is required.',
            // 'features_text.required'  => 'Features text is required.',
            // 'features_mark.required'  => 'Features mark is required.',
            'features_text.*.required' => 'Feature description is required.',
            'features_mark.*.required' => 'Feature selection is required.',
            'features_mark.*.in'       => 'Feature selection must be Yes or No.',
  
        ];

         $validation = Validator::make($request->all(), $rules,$messages);
        if ($validation->fails()) {

            return response()->json([
                'success' => false,
                'errors' => $validation->errors()
            ]);
        }

        // DB::beginTransaction();

        try {
            $billing = Plan::findOrFail($id);

            $billing->name  = $request->name;
            $billing->interval = $request->interval;
            $billing->price = $request->price;
            $billing->note  = $request->note;
            $features = [];
            $texts = $request->features_text ?? [];
            $marks = $request->features_mark ?? [];

            // foreach ($texts as $index => $text) {
            //     $features[] = [
            //         'text' => $text,
            //         'mark' => isset($marks[$index]) ? (int)$marks[$index] : 0,
            //     ];
            // }
            
            foreach ($texts as $index => $text) {
                if (trim($text) !== '') {
                    $features[] = [
                        'text' => $text,
                        'mark' => isset($marks[$index]) ? (int)$marks[$index] : 0,
                    ];
                }
            }

            $billing->points = json_encode($features);

            $billing->save();

            // DB::commit();

        return response()->json([
                'success' => true,
                'message' => 'updated successfully.'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'errors' => ['server' => [$e->getMessage()]]
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function billing_delete(Request $request)
    {
        try {
            $id = base64_decode($request->id);
            $billing = Plan::findOrFail($id);
            $billing->delete();

            return response()->json(['success' => true, 'message' => 'Billing deleted successfully']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()]);
        }
    }

   
    public function studentStatus(Request $request)
    {
        $stu_id=base64_decode($request->id);
        $type = base64_decode($request->type);
    
        if($type == 'disable')
        { 
            $user = User::find($stu_id);
            $user->status = '0';
            $user->save();
            
            return response()->json([
                'success'=>true,
                'type' => $type,
                'message'=>'Status change successfully.'
            ]);
        }
        elseif($type == 'enable')
        {   
            $user = User::find($stu_id);
            $user->status = '1';
            $user->save();
        
            return response()->json([
                'success'=>true,
                'type' => $type,
                'message'=>'Status change successfully.'
            ]);
        }
    }
}
