<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;
use App\Core\TenantContext;
class ConferenceSpeakersController extends Controller
{
    public function index()
    {
        $db = Database::getInstance();

        $conferenceId =
            TenantContext::conferenceId();

        $stmt = $db->prepare("
            SELECT *
            FROM conference_speakers
            WHERE conference_id = ?
            ORDER BY id DESC
        ");

        $stmt->execute([$conferenceId]);

        $speakers =
            $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $this->render(
            'admin/speakers/index',
            [
                'speakers' => $speakers
            ]
        );
    }

    public function create()
    {
        $this->render(
            'admin/speakers/create'
        );
    }

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

        $conferenceId =
            TenantContext::conferenceId();

        $photoPath = null;

        if (
            !empty($_FILES['photo']['tmp_name'])
            && is_uploaded_file($_FILES['photo']['tmp_name'])
        ) {

            $allowedMime = [

                'image/jpeg',
                'image/png',
                'image/webp',
                'image/gif'

            ];

            $mime =
                mime_content_type(
                    $_FILES['photo']['tmp_name']
                );

            if (!in_array($mime, $allowedMime, true)) {

                $_SESSION['error'] =
                    'Invalid image format.';

                header(
                    "Location: /easychair/admin/conference-speakers/create"
                );

                exit;
            }

            $ext =
                strtolower(
                    pathinfo(
                        $_FILES['photo']['name'],
                        PATHINFO_EXTENSION
                    )
                );

            $allowedExt = [

                'jpg',
                'jpeg',
                'png',
                'webp',
                'gif'

            ];

            if (!in_array($ext, $allowedExt, true)) {

                $_SESSION['error'] =
                    'Invalid file extension.';

                header(
                    "Location: /easychair/admin/conference-speakers/create"
                );

                exit;
            }

            if ($_FILES['photo']['size'] > 5 * 1024 * 1024) {

                $_SESSION['error'] =
                    'Image exceeds 5MB limit.';

                header(
                    "Location: /easychair/admin/conference-speakers/create"
                );

                exit;
            }

            $filename =
                'speaker_' .
                time() .
                '_' .
                mt_rand(1000,9999) .
                '.' .
                $ext;

            $target =
                BASE_PATH .
                '/public/uploads/speakers/' .
                $filename;

            move_uploaded_file(
                $_FILES['photo']['tmp_name'],
                $target
            );

            $photoPath =
                'uploads/speakers/' .
                $filename;
        }

        $stmt = $db->prepare("
            INSERT INTO conference_speakers
            (
                conference_id,
                full_name,
                title_en,
                title_ar,
                institution_name,
                bio_en,
                bio_ar,
                photo_path
            )
            VALUES
            (?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $stmt->execute([

            $conferenceId,
            trim($_POST['full_name'] ?? ''),
            trim($_POST['title_en'] ?? ''),
            trim($_POST['title_ar'] ?? ''),
            trim($_POST['institution_name'] ?? ''),
            trim($_POST['bio_en'] ?? ''),
            trim($_POST['bio_ar'] ?? ''),
            $photoPath

        ]);

        $_SESSION['success'] =
            'Speaker created successfully';

        header(
            "Location: /easychair/admin/conference-speakers"
        );

        exit;
    }

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

        $id =
            (int)($_GET['id'] ?? 0);

        $stmt = $db->prepare("
            SELECT *
            FROM conference_speakers
            WHERE id = ?
            LIMIT 1
        ");

        $stmt->execute([$id]);

        $speaker =
            $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$speaker) {
            die("Speaker not found.");
        }

        $this->render(
            'admin/speakers/edit',
            [
                'speaker' => $speaker
            ]
        );
    }

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

        $id =
            (int)($_POST['id'] ?? 0);

        $speakerStmt = $db->prepare("
            SELECT *
            FROM conference_speakers
            WHERE id = ?
            LIMIT 1
        ");

        $speakerStmt->execute([$id]);

        $existing =
            $speakerStmt->fetch(\PDO::FETCH_ASSOC);

        if (!$existing) {
            die("Speaker not found.");
        }

        $photoPath =
            $existing['photo_path'] ?? null;

        if (
            !empty($_FILES['photo']['tmp_name'])
            && is_uploaded_file($_FILES['photo']['tmp_name'])
        ) {

            $allowedMime = [

                'image/jpeg',
                'image/png',
                'image/webp',
                'image/gif'

            ];

            $mime =
                mime_content_type(
                    $_FILES['photo']['tmp_name']
                );

            if (!in_array($mime, $allowedMime, true)) {

                $_SESSION['error'] =
                    'Invalid image format.';

                header(
                    "Location: /easychair/admin/conference-speakers/edit?id=" . $id
                );

                exit;
            }

            $ext =
                strtolower(
                    pathinfo(
                        $_FILES['photo']['name'],
                        PATHINFO_EXTENSION
                    )
                );

            $filename =
                'speaker_' .
                time() .
                '_' .
                mt_rand(1000,9999) .
                '.' .
                $ext;

            $target =
                BASE_PATH .
                '/public/uploads/speakers/' .
                $filename;

            move_uploaded_file(
                $_FILES['photo']['tmp_name'],
                $target
            );

            $photoPath =
                'uploads/speakers/' .
                $filename;
        }

        $stmt = $db->prepare("
            UPDATE conference_speakers
            SET
                full_name = ?,
                title_en = ?,
                title_ar = ?,
                institution_name = ?,
                bio_en = ?,
                bio_ar = ?,
                photo_path = ?
            WHERE id = ?
            LIMIT 1
        ");

        $stmt->execute([

            trim($_POST['full_name'] ?? ''),
            trim($_POST['title_en'] ?? ''),
            trim($_POST['title_ar'] ?? ''),
            trim($_POST['institution_name'] ?? ''),
            trim($_POST['bio_en'] ?? ''),
            trim($_POST['bio_ar'] ?? ''),
            $photoPath,
            $id

        ]);

        $_SESSION['success'] =
            'Speaker updated successfully';

        header(
            "Location: /easychair/admin/conference-speakers"
        );

        exit;
    }

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

        $id =
            (int)($_GET['id'] ?? 0);

        $stmt = $db->prepare("
            DELETE
            FROM conference_speakers
            WHERE id = ?
            LIMIT 1
        ");

        $stmt->execute([$id]);

        $_SESSION['success'] =
            'Speaker deleted successfully';

        header(
            "Location: /easychair/admin/conference-speakers"
        );

        exit;
    }
}
