<?php
namespace Admin\Controllers;

use Admin\Controllers\AdminController;

class AdminBranchBrandingController extends AdminController
{
    public function index()
    {
        requireAdmin();

        $stmt = $this->db->prepare(
            "SELECT bb.*, b.name as branch_name FROM branch_branding bb LEFT JOIN branches b ON bb.branch_id = b.id ORDER BY bb.created_at DESC"
        );
        $stmt->execute();
        $branding = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];

        return $this->adminView('branding', [
            'title' => 'Branch Branding Materials', 'currentPage' => 'branding', 'branding' => $branding,
        ]);
    }

    public function upload()
    {
        requireAdmin();

        $stmt = $this->db->prepare("SELECT id, name, branch_code FROM branches WHERE active = 1 ORDER BY name");
        $stmt->execute();
        $branches = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];

        return $this->adminView('branding_upload', [
            'title' => 'Upload Branding Material', 'currentPage' => 'branding', 'branches' => $branches,
        ]);
    }

    public function processUpload()
    {
        requireAdmin();
        $this->validateCsrf();

        $branchId = (int) ($_POST['branch_id'] ?? 0);
        $materialType = sanitize($_POST['material_type'] ?? '');

        if ($branchId <= 0 || empty($materialType)) {
            flash('error', 'Please select a branch and material type.');
            redirect(BASE_PATH . '/admin/branch-branding/upload');
            return;
        }

        $filePath = $this->handleImageUpload('file', 'branding');
        if (!$filePath) {
            flash('error', 'Failed to upload file.');
            redirect(BASE_PATH . '/admin/branch-branding/upload');
            return;
        }

        $originalName = sanitize($_FILES['file']['name'] ?? '');

        try {
            $stmt = $this->db->prepare(
                "INSERT INTO branch_branding (branch_id, material_type, file_path, original_name, created_at) VALUES (?, ?, ?, ?, NOW())"
            );
            $stmt->execute([$branchId, $materialType, $filePath, $originalName]);
            flash('success', 'Branding material uploaded successfully.');
        } catch (\Exception $e) {
            flash('error', 'Failed to upload: ' . $e->getMessage());
        }
        redirect(BASE_PATH . '/admin/branch-branding');
    }

    public function delete($params)
    {
        requireAdmin();
        $this->validateCsrf();
        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare("SELECT * FROM branch_branding WHERE id = ?");
        $stmt->execute(['id' => $id]);
        $item = $stmt->fetch(\PDO::FETCH_ASSOC);
        if (!$item) {
            flash('error', 'Item not found.');
            redirect(BASE_PATH . '/admin/branch-branding');
            return;
        }

        $this->deleteImageFile($item['file_path']);
        $this->db->prepare("DELETE FROM branch_branding WHERE id = ?")->execute([$id]);
        flash('success', 'Branding material deleted.');
        redirect(BASE_PATH . '/admin/branch-branding');
    }
}
