<?php

namespace App\Http\Controllers\Tele;

use App\Http\Controllers\Controller;
use App\Http\Requests\TeleRecordStoreRequest;
use App\Http\Requests\TeleRecordUpdateRequest;
use App\Models\Outlet;
use App\Models\TeleRecord;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class RecordController extends Controller
{
    // Remove the __construct with $this->middleware(...)

    public function index(Request $request)
    {
        $user     = $request->user();
        $q        = $request->string('q')->toString();
        $outletId = $request->integer('outlet_id');
        $from     = $request->date('from');
        $to       = $request->date('to');
        $hasAudio = $request->filled('has_audio') ? (bool)$request->input('has_audio') : null;

        $records = TeleRecord::query()
            ->with('outlet')
            ->forUser($user)
            ->when($q, function($query) use ($q) {
                $query->where(function($qq) use ($q) {
                    $qq->where('name','like',"%{$q}%")
                       ->orWhere('record_no','like',"%{$q}%")
                       ->orWhere('phone','like',"%{$q}%")
                       ->orWhere('notes','like',"%{$q}%");
                });
            })
            ->when($outletId, fn($query) => $query->where('outlet_id', $outletId))
            ->when($from, fn($query) => $query->whereDate('created_at','>=',$from))
            ->when($to,   fn($query) => $query->whereDate('created_at','<=',$to))
            ->when(!is_null($hasAudio), fn($q2) => $hasAudio ? $q2->whereNotNull('audio_path') : $q2->whereNull('audio_path'))
            ->latest()
            ->paginate(20)
            ->withQueryString();

        $outlets = Outlet::orderBy('brand')->orderBy('location')->get();

        return view('telecalling.records.index', compact('records','outlets'));
    }

    public function create()
    {
        $outlets = Outlet::orderBy('brand')->orderBy('location')->get();
        return view('telecalling.records.create', compact('outlets'));
    }

    public function store(TeleRecordStoreRequest $request)
    {
        $user = $request->user();

        $data = $request->safe()->except(['audio','remove_audio']);
        $data['created_by'] = $user->id;
        if (empty($data['called_at'])) $data['called_at'] = now();

        if ($request->hasFile('audio')) {
            $file = $request->file('audio');
            $dir  = 'tele/audio/'.now()->format('Y/m');
            $name = now()->format('His')."_{$user->id}_".Str::slug(substr($data['name'],0,32)).'.'.$file->getClientOriginalExtension();
            $path = $file->storeAs($dir, $name, 'public');
            $data['audio_path'] = $path;
            $data['audio_mime'] = $file->getClientMimeType();
            $data['audio_size'] = (int) round($file->getSize()/1024);
        }

        TeleRecord::create($data);

        return redirect()->route('tele.records.index')->with('status', 'Record added successfully.');
    }

    public function edit(TeleRecord $record, Request $request)
    {
        $this->authorizeOwnerOrAdmin($record, $request->user());
        $outlets = Outlet::orderBy('brand')->orderBy('location')->get();
        return view('telecalling.records.edit', ['record' => $record, 'outlets' => $outlets]);
    }

    public function update(TeleRecordUpdateRequest $request, TeleRecord $record)
    {
        $this->authorizeOwnerOrAdmin($record, $request->user());

        $data = $request->safe()->except(['audio','remove_audio']);

        if ($request->boolean('remove_audio') && $record->audio_path) {
            Storage::disk('public')->delete($record->audio_path);
            $data['audio_path'] = null;
            $data['audio_mime'] = null;
            $data['audio_size'] = null;
        }

        if ($request->hasFile('audio')) {
            if ($record->audio_path) Storage::disk('public')->delete($record->audio_path);
            $file = $request->file('audio');
            $dir  = 'tele/audio/'.now()->format('Y/m');
            $name = now()->format('His')."_{$request->user()->id}_".Str::slug(substr($data['name'],0,32)).'.'.$file->getClientOriginalExtension();
            $path = $file->storeAs($dir, $name, 'public');
            $data['audio_path'] = $path;
            $data['audio_mime'] = $file->getClientMimeType();
            $data['audio_size'] = (int) round($file->getSize()/1024);
        }

        $record->update($data);

        return redirect()->route('tele.records.index')->with('status', 'Record updated.');
    }

    public function destroy(TeleRecord $record, Request $request)
    {
        $this->authorizeOwnerOrAdmin($record, $request->user());
        $record->delete();
        return back()->with('status', 'Record moved to trash.');
    }

    protected function authorizeOwnerOrAdmin(TeleRecord $record, $user): void
    {
        if (!$user) abort(403);
        if ($user->role === 'admin') return;
        if ($record->created_by !== $user->id) abort(403);
    }
public function audio(TeleRecord $record, Request $request)
{
    $this->authorizeOwnerOrAdmin($record, $request->user());

    if (!$record->audio_path) {
        abort(404);
    }

    $disk = Storage::disk('public');
    if (! $disk->exists($record->audio_path)) {
        abort(404);
    }

    // Stream inline with proper mime; BinaryFileResponse handles range requests
    $mime = $record->audio_mime ?: ($disk->mimeType($record->audio_path) ?? 'audio/mpeg');

    return $disk->response($record->audio_path, null, [
        'Content-Type'   => $mime,
        'Cache-Control'  => 'private, max-age=0, must-revalidate',
    ]);
}

public function download(TeleRecord $record, Request $request)
{
    $this->authorizeOwnerOrAdmin($record, $request->user());

    if (!$record->audio_path) {
        abort(404);
    }

    $disk = Storage::disk('public');
    if (! $disk->exists($record->audio_path)) {
        abort(404);
    }

    $ext = pathinfo($record->audio_path, PATHINFO_EXTENSION);
    $name = $record->record_no
        ? 'record-'.$record->record_no.'.'.$ext
        : basename($record->audio_path);

    return $disk->download($record->audio_path, $name);
}






}
