<?php

namespace App\Http\Controllers;
//namespace App\Exports; 
use Illuminate\Http\Request;

use App\Exports\TemplateExport;
use App\Imports\TemplateImport;
use App\Exports\MobileExport;
use App\Imports\MobileImport;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\Customer;
class AdminWebController extends Controller
{
    //Export Excel (i.e download excel)
    public function downloadTemplate()
    {
       
         return Excel::download(new TemplateExport(), 'Default Process Allocation Template.xlsx');
        //return $response::download(url("resources/templetes/default_allocation_templete.csv"));
    }

    //Import Excel (i.e upload excel)
    public function uploadTemplate(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:xlsx,xls,csv',
        ]);
        Excel::import(new TemplateImport,$request->file('file')->store('temp'));
        //return back();
        return response()->json(['success' => 'File imported successfully!']);
    }

    //

    public function downloadMobileTemplate()
    {
       
         return Excel::download(new MobileExport(), 'Call CRM Delete Allocations.xlsx');
        //return $response::download(url("resources/templetes/default_allocation_templete.csv"));
    }
    public function uploadMobileTemplate(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:xlsx,xls,csv',
        ]);

        $mobileNumbers = Excel::toCollection(new MobileImport,$request->file('file'));

        // Convert the imported data into a flat array of mobile numbers
        $mobileNumbers = $mobileNumbers->flatten()->toArray();

        // $data=new Customer;
        // Soft delete records with the mobile numbers in the imported file
       $records=Customer::whereIn('mobile', $mobileNumbers)->get();
   
       $recordsUpdated = 0;

       foreach ($records as $record) 
       {
        if ($record->flag == 0)
         {
            $record->flag = 1;
            $record->save(); // Save the updated record
            $recordsUpdated++;
        }
     }
     if ($recordsUpdated > 0) {
        return response()->json(['success' => 'Records deleted successfully!']);
    } else {
        return response()->json(['error' => 'Record Not Found or already flagged!']);
    }
        
       
    }

}
