<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Core\Auth;
use App\Core\Database;

class ClientsController extends Controller
{
    public function index(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        
        $pdo = Database::pdo();
        
        // Recherche et filtres
        $search = $_GET['search'] ?? '';
        $status = $_GET['status'] ?? '';
        
        $sql = "SELECT c.*, 
                       COALESCE(COUNT(DISTINCT l.id), 0) as locations_count,
                       COALESCE(COUNT(DISTINCT i.id), 0) as incidents_count
                FROM clients c
                LEFT JOIN locations l ON l.client_id = c.id
                LEFT JOIN incidents i ON i.client_id = c.id
                WHERE 1=1";
        
        $params = [];
        
        if ($search) {
            $sql .= " AND (c.name LIKE :search OR c.email LIKE :search OR c.phone LIKE :search)";
            $params[':search'] = '%' . $search . '%';
        }
        
        if ($status === 'active') {
            $sql .= " AND c.active = 1";
        } elseif ($status === 'inactive') {
            $sql .= " AND c.active = 0";
        }
        
        $sql .= " GROUP BY c.id ORDER BY c.name ASC";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $clients = $stmt->fetchAll();
        
        $this->view('clients/index', [
            'clients' => $clients,
            'search' => $search,
            'status' => $status
        ]);
    }
    
    public function create(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        Auth::requireRole(['admin', 'agent']);
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->store();
            return;
        }
        
        $this->view('clients/create');
    }
    
    public function store(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        Auth::requireRole(['admin', 'agent']);
        
        $pdo = Database::pdo();
        
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $address = trim($_POST['address'] ?? '');
        $city = trim($_POST['city'] ?? '');
        $country = trim($_POST['country'] ?? 'Côte d\'Ivoire');
        $contact_person = trim($_POST['contact_person'] ?? '');
        $contact_phone = trim($_POST['contact_phone'] ?? '');
        $notes = trim($_POST['notes'] ?? '');
        $active = isset($_POST['active']) ? 1 : 1; // Actif par défaut
        
        // Validation
        if (empty($name)) {
            $this->redirect('/clients/create?error=name_required');
            return;
        }
        
        try {
            $stmt = $pdo->prepare("
                INSERT INTO clients (name, email, phone, address, city, country, contact_person, contact_phone, notes, active, created_at)
                VALUES (:name, :email, :phone, :address, :city, :country, :contact_person, :contact_phone, :notes, :active, NOW())
            ");
            
            $stmt->execute([
                ':name' => $name,
                ':email' => $email ?: null,
                ':phone' => $phone ?: null,
                ':address' => $address ?: null,
                ':city' => $city ?: null,
                ':country' => $country,
                ':contact_person' => $contact_person ?: null,
                ':contact_phone' => $contact_phone ?: null,
                ':notes' => $notes ?: null,
                ':active' => $active
            ]);
            
            $this->redirect('/clients?success=created');
        } catch (\PDOException $e) {
            error_log("Error creating client: " . $e->getMessage());
            $this->redirect('/clients/create?error=database');
        }
    }
    
    public function show(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        
        $id = (int)($_GET['id'] ?? 0);
        if (!$id) { $this->redirect('/clients'); }
        
        $pdo = Database::pdo();
        
        // Client info
        $stmt = $pdo->prepare("SELECT * FROM clients WHERE id = ?");
        $stmt->execute([$id]);
        $client = $stmt->fetch();
        
        if (!$client) { $this->redirect('/clients'); }
        
        // Locations
        $locStmt = $pdo->prepare("
            SELECT l.*, COALESCE(COUNT(i.id), 0) as incidents_count
            FROM locations l
            LEFT JOIN incidents i ON i.location_id = l.id
            WHERE l.client_id = ?
            GROUP BY l.id
            ORDER BY l.name
        ");
        $locStmt->execute([$id]);
        $locations = $locStmt->fetchAll();
        
        // Recent incidents
        $incStmt = $pdo->prepare("
            SELECT i.*, s.label as status_label, s.color as status_color, l.name as location_name
            FROM incidents i
            JOIN incident_statuses s ON s.id = i.status_id
            JOIN locations l ON l.id = i.location_id
            WHERE i.client_id = ?
            ORDER BY i.declared_at DESC
            LIMIT 10
        ");
        $incStmt->execute([$id]);
        $incidents = $incStmt->fetchAll();
        
        // Statistics
        $statsStmt = $pdo->prepare("
            SELECT 
                COALESCE(COUNT(*), 0) as total_incidents,
                COALESCE(SUM(CASE WHEN s.key_name IN ('ouvert', 'nouveau') THEN 1 ELSE 0 END), 0) as open_incidents,
                COALESCE(SUM(CASE WHEN s.key_name IN ('clos', 'resolu') THEN 1 ELSE 0 END), 0) as closed_incidents
            FROM incidents i
            LEFT JOIN incident_statuses s ON s.id = i.status_id
            WHERE i.client_id = ?
        ");
        $statsStmt->execute([$id]);
        $stats = $statsStmt->fetch();
        
        $this->view('clients/show', [
            'client' => $client,
            'locations' => $locations,
            'incidents' => $incidents,
            'stats' => $stats
        ]);
    }
    
    public function edit(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        Auth::requireRole(['admin', 'agent']);
        
        $id = (int)($_GET['id'] ?? 0);
        if (!$id) { $this->redirect('/clients'); }
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->update($id);
            return;
        }
        
        $pdo = Database::pdo();
        $stmt = $pdo->prepare("SELECT * FROM clients WHERE id = ?");
        $stmt->execute([$id]);
        $client = $stmt->fetch();
        
        if (!$client) { $this->redirect('/clients'); }
        
        $this->view('clients/edit', ['client' => $client]);
    }
    
    public function update(int $id): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        Auth::requireRole(['admin', 'agent']);
        
        $pdo = Database::pdo();
        
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $address = trim($_POST['address'] ?? '');
        $city = trim($_POST['city'] ?? '');
        $country = trim($_POST['country'] ?? 'Côte d\'Ivoire');
        $contact_person = trim($_POST['contact_person'] ?? '');
        $contact_phone = trim($_POST['contact_phone'] ?? '');
        $notes = trim($_POST['notes'] ?? '');
        $active = isset($_POST['active']) ? 1 : 0;
        
        if (empty($name)) {
            $this->redirect("/clients/edit?id=$id&error=name_required");
            return;
        }
        
        try {
            $stmt = $pdo->prepare("
                UPDATE clients 
                SET name = :name, email = :email, phone = :phone, address = :address, 
                    city = :city, country = :country, contact_person = :contact_person,
                    contact_phone = :contact_phone, notes = :notes, active = :active,
                    updated_at = NOW()
                WHERE id = :id
            ");
            
            $stmt->execute([
                ':name' => $name,
                ':email' => $email ?: null,
                ':phone' => $phone ?: null,
                ':address' => $address ?: null,
                ':city' => $city ?: null,
                ':country' => $country,
                ':contact_person' => $contact_person ?: null,
                ':contact_phone' => $contact_phone ?: null,
                ':notes' => $notes ?: null,
                ':active' => $active,
                ':id' => $id
            ]);
            
            $this->redirect("/clients/show?id=$id&success=updated");
        } catch (\PDOException $e) {
            error_log("Error updating client: " . $e->getMessage());
            $this->redirect("/clients/edit?id=$id&error=database");
        }
    }
    
    public function delete(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        Auth::requireRole(['admin']);
        
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->redirect('/clients');
            return;
        }
        
        $id = (int)($_POST['id'] ?? 0);
        if (!$id) { $this->redirect('/clients'); }
        
        $pdo = Database::pdo();
        
        // Vérifier s'il y a des incidents liés
        $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM incidents WHERE client_id = ?");
        $checkStmt->execute([$id]);
        $incidentCount = (int)$checkStmt->fetchColumn();
        
        if ($incidentCount > 0) {
            $this->redirect("/clients?error=has_incidents&count=$incidentCount");
            return;
        }
        
        try {
            // Supprimer les locations du client d'abord
            $pdo->prepare("DELETE FROM locations WHERE client_id = ?")->execute([$id]);
            
            // Supprimer le client
            $pdo->prepare("DELETE FROM clients WHERE id = ?")->execute([$id]);
            
            $this->redirect('/clients?success=deleted');
        } catch (\PDOException $e) {
            error_log("Error deleting client: " . $e->getMessage());
            $this->redirect('/clients?error=database');
        }
    }
    
    public function toggle(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        Auth::requireRole(['admin', 'agent']);
        
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->redirect('/clients');
            return;
        }
        
        $id = (int)($_POST['id'] ?? 0);
        if (!$id) { $this->redirect('/clients'); }
        
        $pdo = Database::pdo();
        
        try {
            $stmt = $pdo->prepare("UPDATE clients SET active = NOT active WHERE id = ?");
            $stmt->execute([$id]);
            
            $this->redirect("/clients/show?id=$id&success=toggled");
        } catch (\PDOException $e) {
            error_log("Error toggling client: " . $e->getMessage());
            $this->redirect("/clients?error=database");
        }
    }
}
