<?php
namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

use App\Core\Database;

class BaseCrudController
{
    protected $table;

    public function index()
    {
        $db = Database::getInstance();
        $rows = $db->query("SELECT * FROM {$this->table} ORDER BY id DESC")->fetchAll();
        require BASE_PATH."/app/views/crud/index.php";
    }

    public function store()
    {
        $db = Database::getInstance();

        $fields = array_keys($_POST);
        $values = array_values($_POST);

        $columns = implode(",", $fields);
        $placeholders = implode(",", array_fill(0,count($fields),"?" ));

        $stmt = $db->prepare("INSERT INTO {$this->table} ($columns) VALUES ($placeholders)");
        $stmt->execute($values);

        echo json_encode(['status'=>'success']);
    }

    public function delete()
    {
        $db = Database::getInstance();
        $db->prepare("DELETE FROM {$this->table} WHERE id=?")
           ->execute([$_POST['id']]);

        echo json_encode(['status'=>'deleted']);
    }
}
