<?php

namespace App\Http\Controllers;

use App\Models\VoiceLog;
use Illuminate\Http\Request;
use Carbon\Carbon;

class VoiceLogController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:voice_sms_log');
    }

    public function index(Request $request)
    {
        $query = VoiceLog::query();

        // Search by date range
        if ($request->from_date) {
            $from = Carbon::parse($request->from_date)->format('Y-m-d 00:00:00');
            $query->where('created_at', '>=', $from);
        }

        if ($request->to_date) {
            $to = Carbon::parse($request->to_date)->format('Y-m-d 23:59:59');
            $query->where('created_at', '<=', $to);
        }

        // Search by type
        if ($request->type) {
            $query->where('type', $request->type);
        }

        // Search by contact number
        if ($request->contact) {
            $query->where('contact', 'like', '%' . $request->contact . '%');
        }

        $voiceLogs = $query->orderBy('id', 'desc')->paginate(100);
        $types = VoiceLog::groupBy('type')->pluck('type');

        return view('voice_log.index', compact('voiceLogs', 'types'));
    }
}
