<?php

namespace App\Controllers;

use PDO;
use Exception;
use Core\DB;

include realpath(dirname(__DIR__) . '/include/function.php');
include_once realpath(dirname(__DIR__) . '/../config.php');

class SubscriptionPlans
{


    /**
     * Create a new subscription plan
     */
    public function create()
    {

        // Get database connection
        $db = new DB();
        $conn = $db->getConnection();

        try {

            $name = trim($_POST['plan_name'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $price = floatval($_POST['price'] ?? 0);
            $duration_days = intval($_POST['duration_days'] ?? 30);
            $features = trim($_POST['features'] ?? '');
            $status = trim($_POST['status'] ?? 'active');
            $subscription_model = trim($_POST['subscription_model'] ?? 'monthly');

            // Validate required fields
            if (empty($name)) {
                $_SESSION['error'] = 'Plan name is required.';
                header('Location: ?app_route=subscription_plans');
                exit;
            }

            if (empty($features)) {
                $_SESSION['error'] = 'Features are required.';
                header('Location: ?app_route=subscription_plans');
                exit;
            }

            // Test database connection
            if (!$conn) {
                throw new Exception('Database connection not available');
            }

            $stmt = $conn->prepare("
                INSERT INTO subscription_plans 
                (name, description, price, duration_days, features, status, subscription_model, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
            ");

            $result = $stmt->execute([
                $name,
                $description,
                $price,
                $duration_days,
                $features,
                $status,
                $subscription_model
            ]);

            if (!$result) {
                throw new Exception('Failed to execute database query');
            }

            $_SESSION['success'] = 'Subscription plan created successfully.';
            header('Location: ?app_route=subscription_plans');
            exit;
        } catch (Exception $e) {
            error_log("Subscription plan creation error: " . $e->getMessage());
            $_SESSION['error'] = 'Failed to create subscription plan: ' . $e->getMessage();
            header('Location: ?app_route=subscription_plans');
            exit;
        }
    }

    /**
     * Update an existing subscription plan
     */
    public function update()
    {
         // Get database connection
        $db = new DB();
        $conn = $db->getConnection();
        try {
            $plan_id = $_POST['plan_id'] ?? '';
            $name = $_POST['plan_name'] ?? '';
            $description = $_POST['description'] ?? '';
            $price = $_POST['price'] ?? 0;
            $duration_days = $_POST['duration_days'] ?? 30;
            $features = $_POST['features'] ?? '';
            $status = $_POST['status'] ?? 'active';
            $subscription_model = $_POST['subscription_model'] ?? 'monthly';

            if (empty($plan_id) || empty($name)) {
                $_SESSION['error'] = 'Plan ID and name are required';
                header('Location: ?app_route=subscription_plans');
                exit;
            }

            if (empty($features)) {
                $_SESSION['error'] = 'Features are required';
                header('Location: ?app_route=subscription_plans');
                exit;
            }

            $stmt = $conn->prepare("
                UPDATE subscription_plans 
                SET name = ?, description = ?, price = ?, duration_days = ?, features = ?, status = ?, subscription_model = ?, updated_at = NOW()
                WHERE id = ?
            ");

            $stmt->execute([
                $name,
                $description,
                $price,
                $duration_days,
                $features,
                $status,
                $subscription_model,
                $plan_id
            ]);

            $_SESSION['success'] = 'Subscription plan updated successfully';
            header('Location: ?app_route=subscription_plans');
            exit;
        } catch (Exception $e) {
            $_SESSION['error'] = 'Failed to update subscription plan: ' . $e->getMessage();
            header('Location: ?app_route=subscription_plans');
            exit;
        }
    }

    /**
     * Delete a subscription plan
     */
    public function delete()
    {
         // Get database connection
        $db = new DB();
        $conn = $db->getConnection();
        try {
            $plan_id = $_GET['id'] ?? '';

            if (empty($plan_id)) {
                $_SESSION['error'] = 'Plan ID is required';
                header('Location: ?app_route=subscription_plans');
                exit;
            }

            // Check if plan is assigned to any users
            $checkStmt = $conn->prepare("SELECT COUNT(*) FROM isp_accounts WHERE subscription_plan_id = ?");
            $checkStmt->execute([$plan_id]);
            $userCount = $checkStmt->fetchColumn();

            if ($userCount > 0) {
                $_SESSION['error'] = 'Cannot delete plan that is assigned to users. Please reassign users first.';
                header('Location: ?app_route=subscription_plans');
                exit;
            }

            $stmt = $conn->prepare("DELETE FROM subscription_plans WHERE id = ?");
            $stmt->execute([$plan_id]);

            $_SESSION['success'] = 'Subscription plan deleted successfully';
            header('Location: ?app_route=subscription_plans');
            exit;
        } catch (Exception $e) {
            $_SESSION['error'] = 'Failed to delete subscription plan: ' . $e->getMessage();
            header('Location: ?app_route=subscription_plans');
            exit;
        }
    }

    /**
     * Assign plan to ISP user
     */
    public function assignPlan()
    {
         // Get database connection
        $db = new DB();
        $conn = $db->getConnection();
        try {
            $user_id = $_POST['user_id'] ?? '';
            $plan_id = $_POST['plan_id'] ?? '';
            $start_date = $_POST['start_date'] ?? date('Y-m-d');

            if (empty($user_id) || empty($plan_id)) {
                $_SESSION['error'] = 'User and plan selection are required';
                header('Location: ?app_route=subscription_plans');
                exit;
            }

            // Get plan details
            $planStmt = $conn->prepare("SELECT * FROM subscription_plans WHERE id = ?");
            $planStmt->execute([$plan_id]);
            $plan = $planStmt->fetch(PDO::FETCH_ASSOC);

            if (!$plan) {
                $_SESSION['error'] = 'Selected plan not found';
                header('Location: ?app_route=subscription_plans');
                exit;
            }

            // Calculate end date
            $end_date = date('Y-m-d', strtotime($start_date . ' + ' . $plan['duration_days'] . ' days'));

            // Update user's subscription
            $stmt = $conn->prepare("
                UPDATE isp_accounts 
                SET subscription_plan_id = ?, 
                    subscription_start = ?, 
                    subscription_end = ?,
                    updated_at = NOW()
                WHERE id = ?
            ");

            $stmt->execute([
                $plan_id,
                $start_date,
                $end_date,
                $user_id
            ]);

            $_SESSION['success'] = 'Subscription plan assigned successfully';
            header('Location: ?app_route=subscription_plans');
            exit;
        } catch (Exception $e) {
            $_SESSION['error'] = 'Failed to assign subscription plan: ' . $e->getMessage();
            header('Location: ?app_route=subscription_plans');
            exit;
        }
    }

    /**
     * Get all subscription plans
     */
    public function getAllPlans()
    {
         // Get database connection
        $db = new DB();
        $conn = $db->getConnection();
        try {
            $stmt = $conn->prepare("SELECT * FROM subscription_plans ORDER BY created_at DESC");
            $stmt->execute();
            $plans = $stmt->fetchAll(PDO::FETCH_ASSOC);
            return $plans;
        } catch (Exception $e) {
            error_log("Error in getAllPlans: " . $e->getMessage());
            return [];
        }
    }

    /**
     * Get all ISP users for assignment
     */
    public function getAllUsers()
    {
         // Get database connection
        $db = new DB();
        $conn = $db->getConnection();
        try {
            $stmt = $conn->prepare("
                SELECT ia.*, sp.name as current_plan_name 
                FROM isp_accounts ia 
                LEFT JOIN subscription_plans sp ON ia.subscription_plan_id = sp.id 
                ORDER BY ia.created_at DESC
            ");
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            return [];
        }
    }
}
