<?php
namespace BranchAdmin\Controllers;

use App\Core\Controller;

/**
 * Abstract Base Branch Admin Controller
 *
 * Provides common functionality for all branch admin panel controllers.
 * Uses $this->db (PDO) directly for all database operations.
 */
abstract class BranchAdminController extends Controller
{
    private const VIEW_PATH = APP_ROOT . '/branch/Views/';

    /**
     * Render a branch admin view wrapped in the branch layout.
     */
    protected function branchAdminView(string $view, array $data = []): never
    {
        extract($data, EXTR_SKIP);

        $flash_error   = flash('error');
        $flash_success = flash('success');
        $flash_warning = flash('warning');
        $flash_info    = flash('info');
        $csrfToken     = generateCsrfToken();
        $currentUser   = getCurrentUser();
        $title         = $title ?? 'Branch Admin';
        $currentPage   = $currentPage ?? '';
        $branchId      = $_SESSION['branch_id'] ?? 0;
        $branchCode    = $_SESSION['branch_code'] ?? '';

        $viewFile = self::VIEW_PATH . $view . '.php';
        if (!file_exists($viewFile)) {
            http_response_code(500);
            echo "Error: Branch admin view '{$view}' not found at {$viewFile}";
            exit;
        }

        ob_start();
        require $viewFile;
        $content = ob_get_clean();

        $layoutFile = self::VIEW_PATH . 'layout.php';
        if (!file_exists($layoutFile)) {
            echo $content;
            exit;
        }
        require $layoutFile;
        exit;
    }

    /**
     * Get the current branch ID from session.
     */
    protected function getBranchId(): int
    {
        return (int) ($_SESSION['branch_id'] ?? 0);
    }

    /**
     * Get the current branch code from session.
     */
    protected function getBranchCode(): string
    {
        return $_SESSION['branch_code'] ?? '';
    }

    /**
     * Handle image upload with validation.
     */
    protected function handleImageUpload(string $fieldName, string $subDir = ''): ?string
    {
        if (!isset($_FILES[$fieldName]) || $_FILES[$fieldName]['error'] !== UPLOAD_ERR_OK) {
            return null;
        }

        $file = $_FILES[$fieldName];

        if ($file['size'] > 5 * 1024 * 1024) {
            flash('error', 'Image size must be less than 5MB.');
            return null;
        }

        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = finfo_file($finfo, $file['tmp_name']);
        finfo_close($finfo);

        if (!in_array($mimeType, $allowedTypes, true)) {
            flash('error', 'Only JPG, PNG, GIF, and WebP images are allowed.');
            return null;
        }

        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = uniqid('img_', true) . '.' . $extension;
        $uploadDir = PUBLIC_ROOT . '/uploads/' . $subDir;

        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $destination = $uploadDir . '/' . $filename;

        if (!move_uploaded_file($file['tmp_name'], $destination)) {
            flash('error', 'Failed to upload image.');
            return null;
        }

        @chmod($destination, 0644);
        return 'uploads/' . ($subDir ? $subDir . '/' : '') . $filename;
    }

    /**
     * Delete an image file from the server.
     */
    protected function deleteImageFile(?string $imagePath): bool
    {
        if (empty($imagePath)) {
            return false;
        }

        $bp = defined('BASE_PATH') ? BASE_PATH : '';
        if ($bp !== '' && str_starts_with($imagePath, $bp . '/')) {
            $imagePath = substr($imagePath, strlen($bp) + 1);
        }
        $imagePath = ltrim($imagePath, '/');

        if (!str_starts_with($imagePath, 'uploads/')) {
            if (file_exists(PUBLIC_ROOT . '/uploads/' . $imagePath)) {
                $imagePath = 'uploads/' . $imagePath;
            } else {
                return false;
            }
        }

        $fullPath = PUBLIC_ROOT . '/' . $imagePath;
        if (file_exists($fullPath) && is_file($fullPath)) {
            return unlink($fullPath);
        }

        return false;
    }
}
