<?php
namespace App\Controllers;

use Core\View;
use Core\Request;
use Core\Response;
use Core\Validator;
use Core\Auth;
use App\Models\User;
use App\Models\Incident;

class UserController
{
    // ==========================================
    // USER DASHBOARD
    // ==========================================
    public function dashboard()
    {
        $user = Auth::user();
        
        if (!$user) {
            return Response::redirect('/login');
        }

        // Fetch past and current emergencies reported by this specific user.
        // We use a custom query here to join the categories table so we can display the category name.
        $sql = "
            SELECT i.*, c.name as category_name
            FROM incidents i
            LEFT JOIN categories c ON i.category_id = c.id
            WHERE i.victim_id = ?
            ORDER BY i.created_at DESC
        ";
        
        $incidents = Incident::fetchAll($sql, [$user['id']]);

        View::make('user/dashboard')
            ->setLayout('layout')
            ->with([
                'title' => 'My Dashboard - ERCS',
                'meta_description' => 'View your emergency report history and manage your account.',
                'user' => $user,
                'incidents' => $incidents
            ])
            ->render();
    }

    // ==========================================
    // UPDATE PROFILE
    // ==========================================
    public function profileUpdate()
    {
        $user = Auth::user();
        
        if (!$user) {
            return Response::json(['status' => 'error', 'message' => 'Unauthorized'], Response::UNAUTHORIZED);
        }

        $data = Request::all();
        
        $validator = Validator::validate($data)
            ->empty(['full_name', 'phone_number']);
            
        // Check if user is attempting to change their password
        if (!empty($data['password'])) {
            $validator->length(['password' => ['min' => 6, 'message' => 'Password must be at least 6 characters.']]);
        }

        if (!$validator->passes()) {
            return Response::json(['status' => 'error', 'errors' => $validator->errors()], Response::BAD_REQUEST);
        }

        // Ensure the phone number isn't being taken by someone else
        if ($data['phone_number'] !== $user['phone_number']) {
            $existingPhone = User::where('phone_number', $data['phone_number']);
            if ($existingPhone && $existingPhone['id'] !== $user['id']) {
                return Response::json(['status' => 'error', 'message' => 'This phone number is already registered to another account.'], Response::BAD_REQUEST);
            }
        }

        // Prepare data for update
        $updateData = [
            'full_name' => $data['full_name'],
            'phone_number' => $data['phone_number']
        ];

        // Hash new password if provided
        if (!empty($data['password'])) {
            $updateData['password_hash'] = password_hash($data['password'], PASSWORD_DEFAULT);
        }

        $success = User::update($user['id'], $updateData);

        if ($success !== false) {
            // Update session data slightly to reflect new name if needed
            \Core\Session::set('name', $data['full_name']);
            return Response::json(['status' => 'success', 'message' => 'Profile updated successfully.']);
        }

        return Response::json(['status' => 'error', 'message' => 'Failed to update profile.'], Response::INTERNAL_SERVER_ERROR);
    }
}