<?php

namespace App\Http\Controllers;

use App\Models\CaseRecord;
use App\Models\CaseStatement;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class CaseStatementController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = CaseStatement::with(['case', 'recordedByOfficer', 'verifiedByOfficer']);
        
        // Filter by case if provided
        if ($request->has('case_id') && $request->case_id) {
            $query->where('case_id', $request->case_id);
        }
        
        // Filter by statement type if provided
        if ($request->has('statement_type') && $request->statement_type) {
            $query->where('statement_type', $request->statement_type);
        }
        
        // Filter by verification status if provided
        if ($request->has('is_verified')) {
            $query->where('is_verified', $request->is_verified == '1');
        }
        
        // Filter by search term if provided
        if ($request->has('search') && $request->search) {
            $searchTerm = '%' . $request->search . '%';
            $query->where(function($q) use ($searchTerm) {
                $q->where('given_by_name', 'like', $searchTerm)
                  ->orWhere('statement_content', 'like', $searchTerm)
                  ->orWhere('location_taken', 'like', $searchTerm);
            });
        }
        
        // Default sorting by statement_date desc
        $query->orderBy('statement_date', 'desc');
        
        $statements = $query->paginate(15);
        $cases = CaseRecord::all();
        $officers = User::where('is_officer', true)->get();
        
        $statementTypes = [
            'victim' => 'Victim',
            'witness' => 'Witness',
            'suspect' => 'Suspect',
            'officer' => 'Officer',
            'expert' => 'Expert',
        ];
        
        return view('case-statements.index', compact('statements', 'cases', 'statementTypes', 'officers'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(Request $request)
    {
        $caseId = $request->case_id;
        $case = null;
        
        if ($caseId) {
            $case = CaseRecord::findOrFail($caseId);
        }
        
        $cases = CaseRecord::all();
        $officers = User::where('is_officer', true)->get();
        
        $statementTypes = [
            'victim' => 'Victim',
            'witness' => 'Witness',
            'suspect' => 'Suspect',
            'officer' => 'Officer',
            'expert' => 'Expert',
        ];
        
        $idTypes = [
            'national_id' => 'National ID',
            'passport' => 'Passport',
            'drivers_license' => 'Driver\'s License',
            'voter_id' => 'Voter ID',
            'other' => 'Other',
        ];
        
        return view('case-statements.create', compact('case', 'cases', 'officers', 'statementTypes', 'idTypes'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'case_id' => 'required|exists:cases,id',
            'statement_type' => 'required|string|max:50',
            'given_by_name' => 'required|string|max:255',
            'given_by_contact' => 'nullable|string|max:50',
            'given_by_address' => 'nullable|string|max:255',
            'given_by_id_type' => 'nullable|string|max:50',
            'given_by_id_number' => 'nullable|string|max:50',
            'recorded_by_officer_id' => 'required|exists:users,id',
            'statement_date' => 'required|date',
            'statement_content' => 'required|string',
            'location_taken' => 'nullable|string|max:255',
            'is_sworn' => 'boolean',
            'is_signed' => 'boolean',
            'signature_file' => 'nullable|file|mimes:jpeg,png,jpg,pdf|max:2048',
            'audio_recording' => 'nullable|file|mimes:mp3,wav,m4a|max:10240',
            'officer_remarks' => 'nullable|string',
        ]);
        
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }
        
        try {
            $statement = new CaseStatement();
            $statement->case_id = $request->case_id;
            $statement->statement_type = $request->statement_type;
            $statement->given_by_name = $request->given_by_name;
            $statement->given_by_contact = $request->given_by_contact;
            $statement->given_by_address = $request->given_by_address;
            $statement->given_by_id_type = $request->given_by_id_type;
            $statement->given_by_id_number = $request->given_by_id_number;
            $statement->recorded_by_officer_id = $request->recorded_by_officer_id;
            $statement->statement_date = $request->statement_date;
            $statement->statement_content = $request->statement_content;
            $statement->location_taken = $request->location_taken;
            $statement->is_sworn = $request->has('is_sworn');
            $statement->is_signed = $request->has('is_signed');
            $statement->officer_remarks = $request->officer_remarks;
            
            // Handle signature file upload
            if ($request->hasFile('signature_file')) {
                $signatureFile = $request->file('signature_file');
                $signaturePath = $signatureFile->store('statements/signatures', 'public');
                $statement->signature_file_path = $signaturePath;
            }
            
            // Handle audio recording upload
            if ($request->hasFile('audio_recording')) {
                $audioFile = $request->file('audio_recording');
                $audioPath = $audioFile->store('statements/audio', 'public');
                $statement->audio_recording_path = $audioPath;
            }
            
            $statement->save();
            
            // Create a case update for the new statement
            $statement->case->updates()->create([
                'update_type' => 'statement',
                'description' => ucfirst($request->statement_type) . ' statement recorded from ' . $request->given_by_name,
                'officer_id' => Auth::id(),
                'update_date' => now(),
            ]);
            
            return redirect()->route('case-statements.show', $statement->id)
                ->with('success', 'Statement recorded successfully');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Error recording statement: ' . $e->getMessage())
                ->withInput();
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $statement = CaseStatement::with(['case', 'recordedByOfficer', 'verifiedByOfficer'])->findOrFail($id);
        return view('case-statements.show', compact('statement'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        $statement = CaseStatement::findOrFail($id);
        $cases = CaseRecord::all();
        $officers = User::where('is_officer', true)->get();
        
        $statementTypes = [
            'victim' => 'Victim',
            'witness' => 'Witness',
            'suspect' => 'Suspect',
            'officer' => 'Officer',
            'expert' => 'Expert',
        ];
        
        $idTypes = [
            'national_id' => 'National ID',
            'passport' => 'Passport',
            'drivers_license' => 'Driver\'s License',
            'voter_id' => 'Voter ID',
            'other' => 'Other',
        ];
        
        return view('case-statements.edit', compact('statement', 'cases', 'officers', 'statementTypes', 'idTypes'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $validator = Validator::make($request->all(), [
            'case_id' => 'required|exists:cases,id',
            'statement_type' => 'required|string|max:50',
            'given_by_name' => 'required|string|max:255',
            'given_by_contact' => 'nullable|string|max:50',
            'given_by_address' => 'nullable|string|max:255',
            'given_by_id_type' => 'nullable|string|max:50',
            'given_by_id_number' => 'nullable|string|max:50',
            'recorded_by_officer_id' => 'required|exists:users,id',
            'statement_date' => 'required|date',
            'statement_content' => 'required|string',
            'location_taken' => 'nullable|string|max:255',
            'is_sworn' => 'boolean',
            'is_signed' => 'boolean',
            'signature_file' => 'nullable|file|mimes:jpeg,png,jpg,pdf|max:2048',
            'audio_recording' => 'nullable|file|mimes:mp3,wav,m4a|max:10240',
            'officer_remarks' => 'nullable|string',
        ]);
        
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }
        
        try {
            $statement = CaseStatement::findOrFail($id);
            $statement->case_id = $request->case_id;
            $statement->statement_type = $request->statement_type;
            $statement->given_by_name = $request->given_by_name;
            $statement->given_by_contact = $request->given_by_contact;
            $statement->given_by_address = $request->given_by_address;
            $statement->given_by_id_type = $request->given_by_id_type;
            $statement->given_by_id_number = $request->given_by_id_number;
            $statement->recorded_by_officer_id = $request->recorded_by_officer_id;
            $statement->statement_date = $request->statement_date;
            $statement->statement_content = $request->statement_content;
            $statement->location_taken = $request->location_taken;
            $statement->is_sworn = $request->has('is_sworn');
            $statement->is_signed = $request->has('is_signed');
            $statement->officer_remarks = $request->officer_remarks;
            
            // Handle signature file upload
            if ($request->hasFile('signature_file')) {
                // Delete old file if exists
                if ($statement->signature_file_path) {
                    Storage::disk('public')->delete($statement->signature_file_path);
                }
                
                $signatureFile = $request->file('signature_file');
                $signaturePath = $signatureFile->store('statements/signatures', 'public');
                $statement->signature_file_path = $signaturePath;
            }
            
            // Handle audio recording upload
            if ($request->hasFile('audio_recording')) {
                // Delete old file if exists
                if ($statement->audio_recording_path) {
                    Storage::disk('public')->delete($statement->audio_recording_path);
                }
                
                $audioFile = $request->file('audio_recording');
                $audioPath = $audioFile->store('statements/audio', 'public');
                $statement->audio_recording_path = $audioPath;
            }
            
            $statement->save();
            
            return redirect()->route('case-statements.show', $statement->id)
                ->with('success', 'Statement updated successfully');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Error updating statement: ' . $e->getMessage())
                ->withInput();
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        try {
            $statement = CaseStatement::findOrFail($id);
            $caseId = $statement->case_id;
            
            // Delete associated files
            if ($statement->signature_file_path) {
                Storage::disk('public')->delete($statement->signature_file_path);
            }
            
            if ($statement->audio_recording_path) {
                Storage::disk('public')->delete($statement->audio_recording_path);
            }
            
            $statement->delete();
            
            return redirect()->route('cases.show', $caseId)
                ->with('success', 'Statement deleted successfully');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Error deleting statement: ' . $e->getMessage());
        }
    }
    
    /**
     * Verify a statement.
     */
    public function verify(Request $request, string $id)
    {
        try {
            $statement = CaseStatement::findOrFail($id);
            
            if ($statement->is_verified) {
                return redirect()->back()
                    ->with('error', 'Statement has already been verified');
            }
            
            $statement->is_verified = true;
            $statement->verified_by_officer_id = Auth::id();
            $statement->verified_at = now();
            $statement->save();
            
            // Create a case update for the verification
            $statement->case->updates()->create([
                'update_type' => 'statement',
                'description' => ucfirst($statement->statement_type) . ' statement from ' . $statement->given_by_name . ' has been verified',
                'officer_id' => Auth::id(),
                'update_date' => now(),
            ]);
            
            return redirect()->route('case-statements.show', $statement->id)
                ->with('success', 'Statement verified successfully');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Error verifying statement: ' . $e->getMessage());
        }
    }
}
