<?php
declare(strict_types=1);
namespace BranchAdmin\Controllers;

/**
 * Branch Course Fee Controller
 * Branch sets/edits fee per course for their branch.
 */
class BranchCourseFeeController extends BranchBaseController
{
    public function index(): void
    {
        requireBranchAdmin();
        $branchId = $this->getBranchId();

        $courses = [];
        try {
            $stmt = $this->db->query("SELECT id, name, duration FROM courses WHERE active = 1 ORDER BY name");
            $courses = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) {}

        // Fetch existing fees for this branch
        $fees = [];
        try {
            $stmt = $this->db->prepare("SELECT * FROM branch_course_fees WHERE branch_id = :bid AND is_active = 1");
            $stmt->execute([':bid' => $branchId]);
            foreach ($stmt->fetchAll() ?: [] as $f) {
                $fees[$f['course_id']] = $f;
            }
        } catch (\Throwable $e) {}

        $this->branchAdminView('course_fees/index', [
            'title'       => 'Course Fees',
            'currentPage' => 'course_fees',
            'courses'     => $courses,
            'fees'        => $fees,
        ]);
    }

    public function store(): void
    {
        requireBranchAdmin();
        $this->validateCsrf();
        $branchId = $this->getBranchId();

        $courseIds = $_POST['course_id'] ?? [];
        $feeAmounts = $_POST['fee_amount'] ?? [];
        $discounts = $_POST['discount'] ?? [];

        $saved = 0;
        try {
            for ($i = 0; $i < count($courseIds); $i++) {
                $cid = (int)$courseIds[$i];
                $amount = (float)($feeAmounts[$i] ?? 0);
                $discount = (float)($discounts[$i] ?? 0);

                if ($cid <= 0 || $amount <= 0) continue;

                // Check if fee already exists for this branch + course
                $stmt = $this->db->prepare("SELECT id FROM branch_course_fees WHERE branch_id = :bid AND course_id = :cid LIMIT 1");
                $stmt->execute([':bid' => $branchId, ':cid' => $cid]);
                $existing = $stmt->fetch();

                if ($existing) {
                    $this->db->prepare("UPDATE branch_course_fees SET fee_amount = :amt, discount_percentage = :disc, updated_at = NOW() WHERE id = :id")
                        ->execute([':amt' => $amount, ':disc' => $discount, ':id' => $existing['id']]);
                } else {
                    $this->db->prepare("INSERT INTO branch_course_fees (branch_id, course_id, fee_amount, discount_percentage, is_active, created_at, updated_at) VALUES (:bid, :cid, :amt, :disc, 1, NOW(), NOW())")
                        ->execute([':bid' => $branchId, ':cid' => $cid, ':amt' => $amount, ':disc' => $discount]);
                }
                $saved++;
            }
            flash('success', "✅ Saved fee settings for {$saved} course(s).");
        } catch (\Throwable $e) {
            // Table might not exist — auto-create
            try {
                $this->db->exec("CREATE TABLE IF NOT EXISTS branch_course_fees (
                    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
                    branch_id BIGINT UNSIGNED NOT NULL,
                    course_id BIGINT UNSIGNED NOT NULL,
                    fee_amount DECIMAL(10,2) NOT NULL DEFAULT 0,
                    discount_percentage DECIMAL(10,2) NOT NULL DEFAULT 0,
                    is_active TINYINT(1) NOT NULL DEFAULT 1,
                    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    PRIMARY KEY (id),
                    INDEX idx_branch_course (branch_id, course_id)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
                flash('warning', 'Fee table was missing — auto-created. Please save again.');
            } catch (\Throwable $e2) {
                flash('error', 'Failed to save fees: ' . $e->getMessage());
            }
        }
        redirect(BASE_PATH . '/branch/course-fees');
    }

    public function update(?int $id = null): void
    {
        requireBranchAdmin();
        $this->validateCsrf();
        if (!$id || $id <= 0) { flash('error', 'Invalid ID.'); redirect(BASE_PATH . '/branch/course-fees'); }

        $amount = (float)($_POST['fee_amount'] ?? 0);
        $discount = (float)($_POST['discount'] ?? 0);

        try {
            $this->db->prepare("UPDATE branch_course_fees SET fee_amount = :amt, discount_percentage = :disc, updated_at = NOW() WHERE id = :id")
                ->execute([':amt' => $amount, ':disc' => $discount, ':id' => $id]);
            flash('success', 'Fee updated.');
        } catch (\Throwable $e) {
            flash('error', 'Failed: ' . $e->getMessage());
        }
        redirect(BASE_PATH . '/branch/course-fees');
    }
}
