<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models;
class ClientsController extends Controller
{
    public function index()
    {

        // $clients = Models\Client::get();

        $data = [
            'page_title' => 'Dashboard', 
            // 'clients' => $clients
        ];
        return view('clients.index', $data);
    }
    public function fetchDataOld(Request $request)
    {
        $query = Models\Client::query();

        if ($request->filled('search')) {
            $searchTerm = $request->search;
            $query->where(function ($q) use ($searchTerm) {
                $q->where('name', 'like', "%{$searchTerm}%")
                  ->orWhere('email', 'like', "%{$searchTerm}%")
                  ->orWhere('contact_person', 'like', "%{$searchTerm}%");
            });
        }


        if ($request->filled('service')) {
            // $query->where('services',  $request->service);
            // $query->whereJsonContains('services', $request->service);
            $query->where('services', 'LIKE', '%' . $request->service . '%');
        }

        if ($request->filled('billing')) {
            $query->where('pay_mode', $request->billing);
        }

        $clients = $query->orderBy('created_at', 'desc')->paginate(30);

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


    private function buildFilteredQuery(Request $request)
    {
        $query = Models\Client::query();

        if ($request->filled('search')) {
            $searchTerm = $request->search;
            $query->where(function ($q) use ($searchTerm) {
                $q->where('name', 'like', "%{$searchTerm}%")
                  ->orWhere('email', 'like', "%{$searchTerm}%")
                  ->orWhere('contact_person', 'like', "%{$searchTerm}%");
            });
        }

        if ($request->filled('service')) {
            $query->whereJsonContains('services', $request->service);
        }

        if ($request->filled('billing')) {
            $query->where('pay_mode', $request->billing);
        }

        return $query->orderBy('created_at', 'desc');
    }

    /**
     * Your existing AJAX fetch method (Refactored to use the new builder)
     */
    public function fetchData(Request $request)
    {
        $clients = $this->buildFilteredQuery($request)->paginate(30);
        return response()->json($clients);
    }

    /**
     * Handle the Export Request
     */
    public function export(Request $request)
    {
        // Get the filtered data but execute get() instead of paginate()
        $clients = $this->buildFilteredQuery($request)->get();
        $format = $request->input('format', 'csv');

        if ($format === 'pdf') {
            return $this->exportToPdf($clients);
        }

        return $this->exportToCsv($clients);
    }

    /**
     * Generate Native CSV (Opens perfectly in Excel without massive dependencies)
     */
    private function exportToCsv($clients)
    {
        $fileName = 'clients_export_' . date('Y-m-d_H-i') . '.csv';

        $headers = [
            "Content-type"        => "text/csv",
            "Content-Disposition" => "attachment; filename=$fileName",
            "Pragma"              => "no-cache",
            "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
            "Expires"             => "0"
        ];

        $columns = ['ID', 'Company Name', 'Contact Person', 'Email', 'Phone', 'Country', 'Pay Mode', 'Status'];

        $callback = function() use($clients, $columns) {
            $file = fopen('php://output', 'w');
            fputcsv($file, $columns);

            foreach ($clients as $client) {
                $row['ID']  = $client->id;
                $row['Company Name']    = $client->name;
                $row['Contact Person']  = $client->contact_person;
                $row['Email']  = $client->email;
                $row['Phone']  = $client->phone;
                $row['Country']  = $client->country;
                $row['Pay Mode']  = $client->pay_mode;
                $row['Status']  = $client->status;

                fputcsv($file, array_values($row));
            }

            fclose($file);
        };

        return new StreamedResponse($callback, 200, $headers);
    }

    /**
     * Generate PDF
     */
    private function exportToPdf($clients)
    {
        // You will need to create a simple blade view for the PDF layout: resources/views/exports/clients_pdf.blade.php
        $pdf = Pdf::loadView('exports.clients_pdf', ['clients' => $clients])
                  ->setPaper('a4', 'landscape');
        
        return $pdf->download('clients_export_' . date('Y-m-d_H-i') . '.pdf');
    }
}
