<?php

class BiensController {
    private $biensModel;
    private $epargneModel;
    private $dettesModel;

    public function __construct() {
        $this->loadModels();
    }
    
    private function loadModels(): void {
        require_once '/home/dykqnvjf/public_html/bewise/app/models/BiensModel.php';
        require_once '/home/dykqnvjf/public_html/bewise/app/models/Epargne_ctModel.php';
        require_once '/home/dykqnvjf/public_html/bewise/app/models/DettesModel.php';
        
        $this->biensModel = new BiensModel();
        $this->epargneModel = new Epargne_ctModel();
        $this->dettesModel = new DettesModel();
    }

    private function setFlash(string $type, string $message): void {
        $_SESSION['flash'] = compact('type', 'message');
    }

    private function getFlash(): ?array {
        return $_SESSION['flash'] ?? null;
    }

    private function clearFlash(): void {
        unset($_SESSION['flash']);
    }

    private function checkAuthentication(): void {
        if (session_status() === PHP_SESSION_NONE) @session_start();
        if (!isset($_SESSION['user'])) {
            $this->redirect('../index.php/login');
        }
    }

    private function redirect(string $url): void {
        header("Location: $url");
        exit();
    }

    public function index(): void {
        $this->checkAuthentication();
        
        $id_user = $_SESSION['user']['id_utilisateur'];
        
        $data = [
            'biens' => $this->biensModel->getByUser($id_user),
            'epargnes' => $this->epargneModel->getByUser($id_user),
            'dettes' => $this->dettesModel->getByUser($id_user),
            'flash' => $this->getFlash()
        ];

        $this->clearFlash();
        $this->renderView('/home/dykqnvjf/public_html/bewise/app/views/BiensView.php', $data);
    }

    public function store(): void {
        $this->checkAuthentication();

        try {
            $data = $this->prepareBienData($_POST);
            $this->validateBienData($data);

            if ($this->biensModel->insert($data)) {
                $this->setFlashAndRedirectstore('success', 'Bien ajouté avec succès');
            }
            $this->setFlashAndRedirect('danger', 'Erreur lors de l\'ajout du bien');
        } catch (Exception $e) {
            $this->setFlashAndRedirect('danger', 'Erreur: ' . $e->getMessage());
        }
    }

    public function edit(int $id): void {
        $this->checkAuthentication();

        $id_user = $_SESSION['user']['id_utilisateur'];
        $bien = $this->biensModel->getById($id);

        if (!$bien) {
            $this->setFlashAndRedirectedit('danger', 'Bien non trouvé');
        }

        $data = [
            'bien' => $bien,
            'epargnes' => $this->epargneModel->getByUser($id_user),
            'dettes' => $this->dettesModel->getByUser($id_user),
            'flash' => $this->getFlash()
        ];

        $this->clearFlash();
        $this->renderView('/home/dykqnvjf/public_html/bewise/app/views/EditBiensView.php', $data);
    }

    public function update(int $id): void {
        $this->checkAuthentication();

        try {
            $data = $this->prepareBienData($_POST);
            $this->validateBienData($data);

            if ($this->biensModel->update($id, $data)) {
                $this->setFlashAndRedirectupdate('success', 'Bien mis à jour avec succès');
            }
            $this->setFlashAndRedirectstore('danger', 'Erreur lors de la mise à jour');
        } catch (Exception $e) {
            $this->setFlashAndRedirectstore('danger', 'Erreur: ' . $e->getMessage());
        }
    }

    public function delete(int $id): void {
        $this->checkAuthentication();

        try {
            if ($this->biensModel->delete($id)) {
                $this->setFlashAndRedirectdelete('success', 'Bien supprimé avec succès');
            }
            $this->setFlashAndRedirectstore('danger', 'Erreur lors de la suppression');
        } catch (Exception $e) {
            $this->setFlashAndRedirectstore('danger', 'Erreur: ' . $e->getMessage());
        }
    }

    private function prepareBienData(array $postData): array {
        return [
            'id_epargne_ct' => $postData['id_epargne_ct'] ?? null,
            'id_dette' => $postData['id_dette'] ?? null,
            'libelle_bien' => htmlspecialchars($postData['libelle_bien']),
            'type_bien' => $postData['type_bien'],
            'description' => htmlspecialchars($postData['description'] ?? ''),
            'source_financement' => $postData['source_financement'],
            'responsable_gestion' => htmlspecialchars($postData['responsable_gestion'] ?? ''),
            'frequence_utilisation' => $postData['frequence_utilisation'] ?? 'Mensuelle',
            'montant_acquisition' => (float)($postData['montant_acquisition'] ?? 0),
            'date_acquisition' => $postData['date_acquisition'] ?? date('Y-m-d'),
            'valeur_actuelle' => (float)($postData['valeur_actuelle'] ?? 0),
            'taux_depreciation' => (float)($postData['taux_depreciation'] ?? 0),
            'historique_valeurs' => htmlspecialchars($postData['historique_valeurs'] ?? ''),
            'benefice_produit' => (float)($postData['benefice_produit'] ?? 0),
            'statut' => $postData['statut'],
            'categorie_bien' => $postData['categorie_bien']
        ];
    }

    private function validateBienData(array $data): void {
        $requiredFields = ['libelle_bien', 'type_bien', 'source_financement', 'categorie_bien', 'statut'];
        
        foreach ($requiredFields as $field) {
            if (empty($data[$field])) {
                throw new Exception("Le champ $field est requis");
            }
        }
    }

    private function setFlashAndRedirectstore(string $type, string $message): void {
        $this->setFlash($type, $message);
        $this->redirect('../index.php/biens');
    }

    private function setFlashAndRedirectdelete(string $type, string $message): void {
        $this->setFlash($type, $message);
        $this->redirect('../biens');
    }
    
    private function setFlashAndRedirectupdate(string $type, string $message): void {
        $this->setFlash($type, $message);
        $this->redirect('../biens');
    }

    private function setFlashAndedit(string $type, string $message): void {
        $this->setFlash($type, $message);
        $this->redirect('../index.php/biens');
    }
    
    
    private function renderView(string $viewPath, array $data = []): void {
        extract($data);
        require_once $viewPath;
    }
}
?>