<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Customers;
use App\Mail\CustomerMail;
use Illuminate\Support\Facades\Mail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use PDF;
use Excel;
use App\Service\ActivityService;

class CustomerController extends Controller
{
    public function list(Request $request)
    {
        $customers= Customer::all();

        return response()->json($customers);
    }

    public function details(Request $request)
    {

        $customer = Customer::findOrFail($id);

        $response=[
            'Customer'=>$customer,
            'items'=>$items,
        ];

        return response()->json($response);

    }

    public function send_mail(Request $request)
    {

        $customer = Customer::findOrFail($id);

        // Send the email
        Mail::to('recipient@example.com')->send(new CustomerMail($customer));

        $response=[
            'success'=>true,
            'message'=>'Customer sent Successfully'
        ];

        return response()->json($response);

    }

    public function pdf()
    {
        
        $pdf = PDF::loadView('view');

        // return $pdf->download('sample.pdf');
        return $pdf->stream('Customer.pdf');
        
    }

    public function export($data)
    {
        return Excel::download(new Customers($data), 'Customers.xlsx');
    }
       
    public function store(Request $request)
    {
        // Validate the request data
        $request->validate([
           'customer_data' => 'required',
            // Add more validation rules as needed
        ]);

        $data=[
            'name','category_id'
        ];
        
        // Assign valiables to objects
        $obj=[];

        foreach ($data as $key => $value) {
            if(isset($request[$value]) && $request[$value]!=null && $request[$value]!=''){
                $obj[$value]=$request[$value];
            }
        }

        // Create the Customer
        $customer = Customer::create($obj);        

        $response=[
            'Customer'=>$customer,
            'success'=>true,
            'message'=>'Customer Created Successfully'
        ];

        return response()->json($response);
    }

   
    public function update(Request $request)
    {
        
    }

    public function destroy($id)
    {
        $customer = Customer::findOrFail($id);
        $customer->delete();

        //Creating Activities 
        $activity=new ActivityService;
        $activity->activityCreateUpdate('Customer',$customer['id'],'Deleted');

        $response=[
            'success'=>true,
            'message'=>'Customer deleted Successfully'
        ];

        return response()->json($response);
    }

}