<?php
require_once __DIR__ . '/../init.php';
require_once PROJECT_ROOT . '/backend/controllers/common_function.php';
require_once PROJECT_ROOT . '/backend/controllers/db_select_helper.php';

require_once PROJECT_ROOT . '/backend/controllers/AttachmentController.php';
require_once PROJECT_ROOT . '/backend/controllers/UserAksesController.php';

class HeroBannerController
{
    private $conn;   
    private $source = "hero_banner";
    private $att_path = "attachments/hero_banner/";
    private $attachmentController;
    private $userAksesController;

    private $table = "hero_banner h
    LEFT JOIN (
            SELECT 
                A.IDSource,
                A.FileName,
                A.TipeMedia,
                A.FormatFile
            FROM attachment A
            WHERE A.Source = 'hero_banner'
              AND A.IDAttachment = (
                  SELECT MIN(A2.IDAttachment)
                  FROM attachment A2
                  WHERE A2.Source = 'hero_banner'
                    AND A2.IDSource = A.IDSource
              )
        ) AS ATT ON ATT.IDSource = h.IDBanner";
    private $pk = "IDBanner";
    private $sv = "HeroBanner"; 
    protected $displayedColumn = [
        'h.IDBanner',
                'h.titleLine1',
                'h.titleLine1_en',
                'h.titleLine2',
                'h.titleLine2_en',
                'h.titleLine3',
                'h.titleLine3_en',
                'h.description',
                'h.description_en',
                'h.backgroundColor',
        'h.CreateBy',
        'h.CreateAt',
        'h.LastUpdateBy',
        'h.LastUpdateAt',
        [
            'name' => 'ATT.FileName',
            'alias' => 'Image'
        ],
        'ATT.TipeMedia',
        'ATT.FormatFile',
    ];

    public function __construct($conn)
    {
        $this->conn = $conn;
        $this->attachmentController = new AttachmentController($conn);
        $this->userAksesController = new UserAksesController($conn);
    }

     public function select($post)
    {
        $listExclude = [];
        $listSearch = ['titleLine1', 'titleLine2', 'titleLine3', 'description'];
        return runSelect(
            $this->conn,
            $this->table,
            $this->pk,
            $this->displayedColumn,
            $post,
            $listExclude,
            $listSearch
        );
    }

    public function select_old($post)
    {
        try {
            $idBanner = isset($post['IDBanner']) ? intval($post['IDBanner']) : 0;

            $sql = "SELECT
                h.IDBanner,
                h.titleLine1,
                h.titleLine1_en,
                h.titleLine2,
                h.titleLine2_en,
                h.titleLine3,
                h.titleLine3_en,
                h.description,
                h.description_en,
                h.backgroundColor,
                a.FileName AS BannerImage
            FROM hero_banner h
            LEFT JOIN attachment a
                ON a.IDSource = h.IDBanner
                AND a.Source = ?
                AND a.TipeMedia = 'Image'
                AND a.Urutan = 1
            WHERE 1 = 1";

            if ($idBanner > 0) {
                $sql .= " AND h.IDBanner = ?";
            }

            $sql .= " ORDER BY h.IDBanner DESC LIMIT 1";

            $stmt = $this->conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Prepare gagal (select hero banner): " . $this->conn->error);
            }

            if ($idBanner > 0) {
                $stmt->bind_param("si", $this->source, $idBanner);
            } else {
                $stmt->bind_param("s", $this->source);
            }

            $stmt->execute();
            $result = $stmt->get_result();
            $listData = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
 
            return [
                "Status" => 1,
                "Keterangan" => "",
                "list_data" => $listData,
            ];
        } catch (Exception $e) {
            return [
                "Status" => 0,
                "Keterangan" => $e->getMessage(),
                "list_data" => [],
            ];
        }
    }

    public function update($post, $files)
    {
        try {
            $clean = function ($value) {
                if (is_null($value)) {
                    return '';
                }
                return htmlspecialchars(trim(strip_tags($value)), ENT_QUOTES, 'UTF-8');
            };

            $IDBanner = isset($post['IDBanner']) ? intval($post['IDBanner']) : 0;
            $isUpdate = $IDBanner > 0;

            $titleLine1 = $clean($post['titleLine1'] ?? '');
            $titleLine1_en = $clean($post['titleLine1_en'] ?? '');
            $titleLine2 = $clean($post['titleLine2'] ?? '');
            $titleLine2_en = $clean($post['titleLine2_en'] ?? '');
            $titleLine3 = $clean($post['titleLine3'] ?? '');
            $titleLine3_en = $clean($post['titleLine3_en'] ?? '');
            $description = $clean($post['description'] ?? '');
            $description_en = $clean($post['description_en'] ?? '');
            $backgroundColor = $clean($post['backgroundColor'] ?? '');
            $clearBannerImage = isset($post['clearBannerImage']) && $post['clearBannerImage'] === '1';
            $clearBackgroundColor = isset($post['clearBackgroundColor']) && $post['clearBackgroundColor'] === '1';
            $currentImage = $clean($post['BannerImageCurrent'] ?? '');

            if (empty($titleLine1)) {
                throw new Exception("Title Line 1 wajib diisi");
            }

            if ($clearBackgroundColor) {
                $backgroundColor = '';
            } elseif (!empty($backgroundColor) && !$this->isValidHexColor($backgroundColor)) {
                throw new Exception("Background Color harus berupa kode HEX valid, contoh #000000");
            }

            $UserLogin = $this->getUserLogin($post['IDUserLogin'] ?? '', $isUpdate);

            return runWithTransaction($this->conn, function ($conn) use (
                $isUpdate,
                $IDBanner,
                $titleLine1,
                $titleLine1_en,
                $titleLine2,
                $titleLine2_en,
                $titleLine3,
                $titleLine3_en,
                $description,
                $description_en,
                $backgroundColor,
                $clearBannerImage,
                $currentImage,
                $UserLogin,
                $files
            ) {
                $NewID = $IDBanner;

                if ($isUpdate) {
                    $sql = "UPDATE hero_banner
                        SET
                            titleLine1 = ?,
                            titleLine1_en = ?,
                            titleLine2 = ?,
                            titleLine2_en = ?,
                            titleLine3 = ?,
                            titleLine3_en = ?,
                            description = ?,
                            description_en = ?,
                            backgroundColor = ?,
                            LastUpdateBy = ?,
                            LastUpdateAt = NOW()
                        WHERE IDBanner = ?";

                    $stmt = $conn->prepare($sql);
                    if (!$stmt) {
                        throw new Exception("Prepare gagal (update hero banner): " . $conn->error);
                    }

                    $stmt->bind_param(
                        "ssssssssssi",
                        $titleLine1,
                        $titleLine1_en,
                        $titleLine2,
                        $titleLine2_en,
                        $titleLine3,
                        $titleLine3_en,
                        $description,
                        $description_en,
                        $backgroundColor,
                        $UserLogin,
                        $IDBanner
                    );
                    $stmt->execute();
                    $stmt->close();
                } else {
                    $sql = "INSERT INTO hero_banner (
                        titleLine1,
                        titleLine1_en,
                        titleLine2,
                        titleLine2_en,
                        titleLine3,
                        titleLine3_en,
                        description,
                        description_en,
                        backgroundColor,
                        CreateBy,
                        CreateAt
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";

                    $stmt = $conn->prepare($sql);
                    if (!$stmt) {
                        throw new Exception("Prepare gagal (insert hero banner): " . $conn->error);
                    }

                    $stmt->bind_param(
                        "ssssssssss",
                        $titleLine1,
                        $titleLine1_en,
                        $titleLine2,
                        $titleLine2_en,
                        $titleLine3,
                        $titleLine3_en,
                        $description,
                        $description_en,
                        $backgroundColor,
                        $UserLogin
                    );
                    $stmt->execute();
                    $NewID = $conn->insert_id;
                    $stmt->close();
                }

                if ($clearBannerImage) {
                    if (!empty($currentImage)) {
                        $deleteResult = $this->attachmentController->delete_all_source([
                            'Source' => $this->source,
                            'IDSource' => $NewID,
                            'PathFile' => $this->att_path,
                        ]);

                        if ($deleteResult['Status'] != 1) {
                            throw new Exception($deleteResult['Keterangan']);
                        }
                    } else {
                        $stmt = $conn->prepare("DELETE FROM attachment WHERE Source = ? AND IDSource = ?");
                        if (!$stmt) {
                            throw new Exception("Prepare gagal (delete attachment): " . $conn->error);
                        }
                        $stmt->bind_param("si", $this->source, $NewID);
                        $stmt->execute();
                        $stmt->close();
                    }
                }

                if (isset($files['BannerImage']) && $files['BannerImage']['error'] === UPLOAD_ERR_OK) {
                    $oldData = [
                        'BannerImage' => $currentImage,
                    ];

                    $uploadResult = g_uploadFile(
                        'BannerImage',
                        $oldData,
                        'BannerImage',
                        $NewID,
                        $this->att_path,
                        ['jpg', 'jpeg', 'png', 'gif', 'webp'],
                        'Image'
                    );

                    if ($uploadResult['Status'] != 1) {
                        throw new Exception("Upload gagal: " . $uploadResult['Keterangan']);
                    }

                    $fileName = $uploadResult['FileUniqueName'];
                    $formatFile = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

                    $attachPost = [
                        'Source' => $this->source,
                        'IDSource' => $NewID,
                        'FileName' => $fileName,
                        'NamaAttachment' => 'Banner Image',
                        'TipeMedia' => 'Image',
                        'FormatFile' => $formatFile,
                        'Urutan' => 1,
                        'updateAll' => 1,
                    ];

                    $attachResult = $this->attachmentController->update($attachPost, $UserLogin);
                    if ($attachResult['Status'] != 1) {
                        throw new Exception($attachResult['Keterangan']);
                    }
                }

                return [
                    'Status' => 1,
                    'Keterangan' => $isUpdate ? 'Hero banner berhasil diperbarui' : 'Hero banner berhasil ditambahkan',
                    'ID' => $NewID,
                ];
            });
        } catch (Exception $e) {
            return [
                'Status' => 0,
                'Keterangan' => $e->getMessage(),
            ];
        }
    }

    private function getUserLogin($IDUserLogin, $isUpdate)
    {
        $AksesNeeded = $isUpdate ? $this->sv . '.Modify' : $this->sv . '.Add';

        $userAksesFilterParam = [
            ['IDUser', $IDUserLogin, 1],
        ];

        $userAksesselectParam = [
            'filters' => $userAksesFilterParam,
            'rows_per_page' => 1,
            'page_number' => 1,
            'no_count' => true,
        ];

        $userAksesresult = $this->userAksesController->select($userAksesselectParam);
        if ($userAksesresult['Status'] != 1 || empty($userAksesresult['list_data'])) {
            throw new Exception($userAksesresult['Keterangan'] ?? 'User tidak ditemukan');
        }

        $listAkses = array_column($userAksesresult['list_data'], 'AksesName');
        if (!in_array($AksesNeeded, $listAkses)) {
            throw new Exception('User tidak memiliki otoritas akses - [' . $AksesNeeded . ']');
        }

        return $userAksesresult['Username'];
    }

    private function isValidHexColor(string $color): bool
    {
        $normalized = trim($color);
        return (bool) preg_match('/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', $normalized);
    }
}
