<?php
require_once __DIR__ . '/../../../Models/SubscriptionPlan.php';
require_once __DIR__ . '/../../../Models/VendorSubscription.php';

class SubscriptionController {
    public function plans() {
        $planModel = new SubscriptionPlan();
        
        $page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
        $perPage = 10;
        
        $result = $planModel->paginatePlans($page, $perPage);
        $plans = $result['data'];
        
        $total = $result['total'];
        $totalPages = ceil($total / $perPage);

        require __DIR__ . '/../../../../views/admin/subscriptions/plans.php';
    }

    public function vendors() {
        $subModel = new VendorSubscription();
        
        $page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
        $perPage = 10;
        
        $result = $subModel->paginateWithDetails($page, $perPage);
        $subscriptions = $result['data'];
        
        $total = $result['total'];
        $totalPages = ceil($total / $perPage);

        require __DIR__ . '/../../../../views/admin/subscriptions/vendors.php';
    }

    public function storePlan() {
        $planModel = new SubscriptionPlan();
        
        $durationMonths = (int)($_POST['duration_months'] ?? 1);
        $billingCycle = ($durationMonths >= 12) ? 'yearly' : 'monthly';
        
        $insertData = [
            'name_en' => $_POST['name_en'],
            'name_ar' => $_POST['name_ar'],
            'price' => $_POST['price'],
            'billing_cycle' => $billingCycle,
            'ads_quota' => isset($_POST['ads_quota']) && $_POST['ads_quota'] !== '' ? (int)$_POST['ads_quota'] : 0,
            'max_maids' => isset($_POST['max_maids']) && $_POST['max_maids'] !== '' ? (int)$_POST['max_maids'] : null,
            'interview_requests_limit' => isset($_POST['interview_requests_limit']) && $_POST['interview_requests_limit'] !== '' ? (int)$_POST['interview_requests_limit'] : null,
            'status' => 'active'
        ];
        
        $planId = $planModel->insert($insertData);
        
        // Parse and store features in subscription_plan_features table
        $featuresEn = array_values(array_filter(array_map('trim', explode("\n", $_POST['features_en'] ?? ''))));
        $featuresAr = array_values(array_filter(array_map('trim', explode("\n", $_POST['features_ar'] ?? ''))));
        
        $db = Database::getInstance();
        $maxLoops = max(count($featuresEn), count($featuresAr));
        
        for ($i = 0; $i < $maxLoops; $i++) {
            $textEn = $featuresEn[$i] ?? ($featuresAr[$i] ?? '');
            $textAr = $featuresAr[$i] ?? ($featuresEn[$i] ?? '');
            
            if ($textEn !== '' || $textAr !== '') {
                $stmt = $db->prepare("
                    INSERT INTO subscription_plan_features (plan_id, feature_text_en, feature_text_ar, sort_order)
                    VALUES (?, ?, ?, ?)
                ");
                $stmt->execute([$planId, $textEn, $textAr, $i]);
            }
        }
        
        header("Location: ?page=subscription_plans&success=Plan added");
    }

    public function updatePlan() {
        $planModel = new SubscriptionPlan();
        $id = (int)($_POST['id'] ?? 0);
        
        $durationMonths = (int)($_POST['duration_months'] ?? 1);
        $billingCycle = ($durationMonths >= 12) ? 'yearly' : 'monthly';
        
        $updateData = [
            'name_en' => $_POST['name_en'],
            'name_ar' => $_POST['name_ar'],
            'price' => $_POST['price'],
            'billing_cycle' => $billingCycle,
            'ads_quota' => isset($_POST['ads_quota']) && $_POST['ads_quota'] !== '' ? (int)$_POST['ads_quota'] : 0,
            'max_maids' => isset($_POST['max_maids']) && $_POST['max_maids'] !== '' ? (int)$_POST['max_maids'] : null,
            'interview_requests_limit' => isset($_POST['interview_requests_limit']) && $_POST['interview_requests_limit'] !== '' ? (int)$_POST['interview_requests_limit'] : null,
            'status' => $_POST['status'] ?? 'active'
        ];
        
        $planModel->update($id, $updateData);
        
        // Re-sync features
        $db = Database::getInstance();
        $db->prepare("DELETE FROM subscription_plan_features WHERE plan_id = ?")->execute([$id]);
        
        $featuresEn = array_values(array_filter(array_map('trim', explode("\n", $_POST['features_en'] ?? ''))));
        $featuresAr = array_values(array_filter(array_map('trim', explode("\n", $_POST['features_ar'] ?? ''))));
        $maxLoops = max(count($featuresEn), count($featuresAr));
        
        for ($i = 0; $i < $maxLoops; $i++) {
            $textEn = $featuresEn[$i] ?? ($featuresAr[$i] ?? '');
            $textAr = $featuresAr[$i] ?? ($featuresEn[$i] ?? '');
            
            if ($textEn !== '' || $textAr !== '') {
                $stmt = $db->prepare("
                    INSERT INTO subscription_plan_features (plan_id, feature_text_en, feature_text_ar, sort_order)
                    VALUES (?, ?, ?, ?)
                ");
                $stmt->execute([$id, $textEn, $textAr, $i]);
            }
        }
        
        header("Location: ?page=subscription_plans&success=Plan updated");
    }

    public function deletePlan() {
        $planModel = new SubscriptionPlan();
        $id = $_GET['id'] ?? 0;
        
        // Safety Check: Verify if any vendor is subscribed to this plan
        $db = Database::getInstance();
        $stmt = $db->prepare("SELECT COUNT(*) FROM vendor_subscriptions WHERE plan_id = ?");
        $stmt->execute([$id]);
        $count = $stmt->fetchColumn();
        
        if ($count > 0) {
            header("Location: ?page=subscription_plans&error=Cannot delete plan because vendors are currently subscribed to it. Please deactivate the plan instead!");
            exit;
        }
        
        $planModel->delete($id);
        header("Location: ?page=subscription_plans&success=Plan deleted");
    }
}
