<?php
namespace App\Models;

use App\Core\Database;

class Submission
{
    protected $db;

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

    /* =====================================
       LIST SUBMISSIONS (ORG SAFE)
    ===================================== */
    public function all()
    {
        if (function_exists('is_superadmin') && is_superadmin()) {
            return $this->db->query("
                SELECT s.*
                FROM submissions s
                ORDER BY s.id DESC
            ")->fetchAll();
        }

        $orgId = current_org_id();

        $stmt = $this->db->prepare("
            SELECT s.*
            FROM submissions s
            JOIN conferences c ON c.id = s.conference_id
            WHERE c.org_id = ?
            ORDER BY s.id DESC
        ");

        $stmt->execute([$orgId]);
        return $stmt->fetchAll();
    }

    /* =====================================
       FIND SUBMISSION (ORG SAFE)
    ===================================== */
    public function find($id)
    {
        if (function_exists('is_superadmin') && is_superadmin()) {
            $stmt = $this->db->prepare("
                SELECT * FROM submissions WHERE id = ?
            ");
            $stmt->execute([$id]);
            return $stmt->fetch();
        }

        $orgId = current_org_id();

        $stmt = $this->db->prepare("
            SELECT s.*
            FROM submissions s
            JOIN conferences c ON c.id = s.conference_id
            WHERE s.id = ?
            AND c.org_id = ?
        ");

        $stmt->execute([$id, $orgId]);
        return $stmt->fetch();
    }

    /* =====================================
       CREATE SUBMISSION
    ===================================== */
    public function create($data)
    {
        $stmt = $this->db->prepare("
            INSERT INTO submissions
            (conference_id, title, abstract, author_id)
            VALUES (?, ?, ?, ?)
        ");

        return $stmt->execute([
            $data['conference_id'],
            $data['title'],
            $data['abstract'],
            $_SESSION['user']['id']
        ]);
    }
}
