<?php
class IntegrationController {
    private $db;
    public function __construct() { $this->db = Database::getInstance(); }

    public function index() {
        $cid = Auth::user()['company_id'];
        $connected = $this->db->fetchAll("SELECT * FROM integrations WHERE company_id=? AND deleted_at IS NULL", [$cid]);
        $connectedMap = []; foreach ($connected as $c) { $connectedMap[$c['provider']] = $c; }
        require 'app/views/integrations/index.php';
    }

    public function configure() {
        $provider = $_GET['provider'] ?? ''; $cid = Auth::user()['company_id'];
        $integration = $this->db->fetch("SELECT * FROM integrations WHERE company_id=? AND provider=? AND deleted_at IS NULL", [$cid, $provider]);
        require 'app/views/integrations/configure.php';
    }

    public function save() {
        CSRF::verify(); $cid = Auth::user()['company_id']; $provider = $_POST['provider'] ?? '';
        $existing = $this->db->fetch("SELECT id FROM integrations WHERE company_id=? AND provider=?", [$cid, $provider]);
        $data = ['company_id' => $cid, 'provider' => $provider, 'status' => $_POST['status'] ?? 'inactive', 'settings' => json_encode($_POST['settings'] ?? [])];
        if ($existing) { $this->db->update('integrations', $data, 'id = ?', [$existing['id']]); }
        else { $this->db->insert('integrations', $data); }
        flash('success', ucfirst($provider) . ' integration saved.'); redirect('?page=integrations');
    }
}
