<?php

namespace App\Http\Controllers;

use App\Models\Action;
use App\Models\AudAuditTrail;
use App\Models\District;
use App\Models\Partner;
use App\Models\PartnerCategory;

use App\Models\Service;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class PartnerController extends Controller
{


    function list(){
    	$partner = Partner::all();
    	return view('partner.list')->with(['partners'=>$partner]);
    }

    function index(){
        $districts = District::all();
    	return view('partner.index', compact('districts'));
    }

    function process(Request $request){
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:180'],
            'contactperson' => ['nullable', 'string', 'max:180'],
            'contact' => ['nullable', 'string', 'max:80'],
            'location' => ['nullable', 'string', 'max:500'],
            'districtids' => ['nullable', 'array'],
            'districtids.*' => ['integer', 'exists:districts,id'],
        ]);

    	$partner = new Partner();

    	$partner->name = $validated['name'];
    	$partner->contact_person = $validated['contactperson'] ?? null;
    	$partner->contact = $validated['contact'] ?? null;
    	$partner->locations = $validated['location'] ?? null;
        $partner->districts = isset($validated['districtids']) ? implode(',', $validated['districtids']) : null;

    	if ($partner->save()) {
            return redirect(url("partner/list"))->with('message', 'Partner Details successfully saved');
        } else {
            return redirect(url("partner/index"))->with('message', 'Partner Details failed to saved');
        }
    }

    function update(Request $request){
        $validated = $request->validate([
            'id' => ['required', 'integer', 'exists:partners,id'],
            'name' => ['required', 'string', 'max:180'],
            'contactperson' => ['nullable', 'string', 'max:180'],
            'contact' => ['nullable', 'string', 'max:80'],
            'location' => ['nullable', 'string', 'max:500'],
            'districtids' => ['nullable', 'array'],
            'districtids.*' => ['integer', 'exists:districts,id'],
        ]);

    	$partner = Partner::findOrFail($validated['id']);

    	$partner->name = $validated['name'];
    	$partner->contact_person = $validated['contactperson'] ?? null;
    	$partner->contact = $validated['contact'] ?? null;
    	$partner->locations = $validated['location'] ?? null;
        $partner->districts = isset($validated['districtids']) ? implode(',', $validated['districtids']) : null;
        $partner->updated_by = Auth::id();

    	if ($partner->save()) {
            return redirect(url("partner/list"))->with('message', 'Partner Details successfully saved');
        } else {
            return redirect(url("partner/index"))->with('message', 'Partner Details failed to saved');
        }
    }

    function category(){
        return view('partner.category');
    }

    function processcategory(Request $request){
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:150'],
        ]);
        $category = new PartnerCategory();

        $category->name = $validated['name'];

        if ($category->save()) {
            return redirect(url("partner/category"))->with('message', 'Partner Category successfully saved');
        } else {
            return redirect(url("partner/category"))->with('message', 'Partner Category failed to saved');
        }
    }

    function updatecategory(Request $request){
        $validated = $request->validate([
            'id' => ['required', 'integer', 'exists:partner_categories,id'],
            'name' => ['required', 'string', 'max:150'],
        ]);
        $category = PartnerCategory::findOrFail($validated['id']);
        $category->name = $validated['name'];
        if ($category->save()) {
            return redirect(url("partner/categorylist"))->with('message', 'Partner Category successfully updated');
        }
        return redirect(url("partner/categorylist"))->with('message', 'Partner Category failed to update');
    }

    function categorylist(){
        $categories = PartnerCategory::all();
        return view('partner.categorylist')->with(['category'=>$categories]);
    }

    function service(Request $request){
        $formvalues = $request;
        $id = isset($formvalues['id']) ? decrypt($formvalues['id']) : null;
        $details = [];
        if (!is_null($id)){
            $servicedetails = Service::find($id);
            if($servicedetails){
                $details['id'] = encrypt($servicedetails->id);
                $details['name'] = $servicedetails->name;
                $details['status'] = $servicedetails->status;
            }
        }
        return view('partner.services', compact('details'));
    }

    function services(){
        $services = Service::get();

        return view('partner.services_list', compact('services'));
    }

    function process_service(Request $request){
        $request->validate([
            'id' => ['nullable', 'string', 'max:255'],
            'name' => ['required', 'string', 'max:180'],
            'status' => ['nullable', 'integer', 'in:0,1'],
        ]);
        $formvalues = $request; $serviceModel = new Service();
        $now = date_create('now', timezone_open('Africa/Kampala'))->format('Y-m-d H:i:s');
        $userid = Auth::user()->id;

        $postdata = $serviceModel->processvalues($formvalues, $userid, $now);
        if(isset($postdata['success_message'])){
            $logging = $this->auditrail;
            $logdata['resource'] = "Partner Services";
            $logdata['action'] = "Creating new Service [".$formvalues['name']."]";
            $logdata['response'] = 'Adding a new Service has been successfull';
            $logdata['status'] = "1";
            $logdata['ip_address'] = \Request::ip();
            $logdata['mac_address'] = 'Unavailable';
            $logdata['browser'] = request()->userAgent();
            $logdata['date'] = date("Y-m-d", strtotime($now));
            $logdata['now'] = $now;
            $logdata['userid'] = Auth::user()->id;
            $logging->postLogData($logdata);

            return back()->with('success_message', $postdata['success_message']);
        }else{
            $logging = $this->auditrail;
            $logdata['resource'] = "Partner Services";
            $logdata['action'] = "Creating new Service";
            $logdata['response'] = 'Adding a new Service has failed';
            $logdata['status'] = "0";
            $logdata['ip_address'] = \Request::ip();
            $logdata['mac_address'] = 'Unavailable';
            $logdata['browser'] = request()->userAgent();
            $logdata['date'] = date("Y-m-d", strtotime($now));
            $logdata['now'] = $now;
            $logdata['userid'] = Auth::user()->id;
            $logging->postLogData($logdata);

            return back()->with('error_message', $postdata['error_message']);
        }

    }
}
