<?php
namespace Controllers;

use Models\Database;

class SocialController {
    private $pdo;

    public function __construct() {
        $this->pdo = Database::getInstance()->getConnection();
    }

    public function index() {
        $data['sociales'] = $this->pdo->query("
            SELECT *
            FROM social_settings
            ORDER BY id ASC
        ")->fetchAll();

        $this->loadInDashboard('index.php', $data);
    }

    public function create() {
        $this->loadInDashboard('form.php');
    }

    public function store() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $stmt = $this->pdo->prepare("
                INSERT INTO social_settings (keyname, label, rate, gross_base)
                VALUES (?, ?, ?, ?)
            ");
            $stmt->execute([
                $_POST['keyname'], $_POST['label'], $_POST['rate'], $_POST['gross_base']
            ]);
            header('Location: /social-settings');
            exit;
        }
    }

    public function edit() {
        $id = $_GET['id'];
        $stmt = $this->pdo->prepare("SELECT * FROM social_settings WHERE id = ?");
        $stmt->execute([$id]);
        $data['sociales'] = $stmt->fetch();

        //$data['employees'] = $this->pdo->query("SELECT id, CONCAT(first_name, ' ', last_name) AS name FROM employees")->fetchAll();

        $this->loadInDashboard('form.php', $data);
    }

    public function update() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $stmt = $this->pdo->prepare("
                UPDATE social_settings
                SET keyname=?, label=?, rate=?, gross_base=?
                WHERE id=?
            ");
            $stmt->execute([
                $_POST['keyname'], $_POST['label'], $_POST['rate'], $_POST['gross_base'], $_POST['id']
            ]);
            header('Location: /social-settings');
            exit;
        }
    }

    public function delete() {
        if (isset($_POST['id'])) {
            $stmt = $this->pdo->prepare("DELETE FROM social_settings WHERE id = ?");
            $stmt->execute([$_POST['id']]);
            header('Location: /social-settings');
            exit;
        }
    }

    private function loadInDashboard($viewFile, $data = []) {
        extract($data);
        $viewPath = __DIR__ . '/../views/social/' . $viewFile;
        if (!file_exists($viewPath)) {
            throw new \Exception("Vue $viewFile introuvable");
        }
        $view = $viewPath;
        require __DIR__ . '/../views/dashboard.php';
    }
}