<?php
require_once '../includes/User.php';
require_once '../includes/db_config.php';

header('Content-Type: application/json');

if (!User::isLoggedIn() || !User::isAdmin()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$pdo = getDBConnection();
$action = $_GET['action'] ?? $_POST['action'] ?? '';

try {
    switch ($action) {
        case 'get_subscriptions':
            $stmt = $pdo->prepare("
                SELECT s.*, u.name as customer_name, u.email as customer_email
                FROM subscriptions s
                LEFT JOIN users u ON s.user_id = u.id
                ORDER BY s.created_at DESC
            ");
            $stmt->execute();
            $subscriptions = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'subscriptions' => $subscriptions
            ]);
            break;
        
        case 'get_subscription':
            $id = $_GET['id'] ?? 0;
            $stmt = $pdo->prepare("SELECT * FROM subscriptions WHERE id = ?");
            $stmt->execute([$id]);
            $subscription = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($subscription) {
                echo json_encode([
                    'success' => true,
                    'subscription' => $subscription
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Subscription not found'
                ]);
            }
            break;
        
        case 'save_subscription':
            $id = $_POST['id'] ?? null;
            $user_id = $_POST['user_id'];
            $plan_name = $_POST['plan_name'];
            $price = $_POST['price'];
            $max_usage = $_POST['max_usage'];
            $start_date = $_POST['start_date'];
            $end_date = $_POST['end_date'];
            $status = $_POST['status'];
            
            if ($id) {
                $stmt = $pdo->prepare("
                    UPDATE subscriptions 
                    SET user_id = ?, plan_name = ?, price = ?, max_usage = ?, 
                        start_date = ?, end_date = ?, status = ?
                    WHERE id = ?
                ");
                $stmt->execute([$user_id, $plan_name, $price, $max_usage, $start_date, $end_date, $status, $id]);
                $message = 'Subscription updated successfully';
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO subscriptions (user_id, plan_name, price, max_usage, start_date, end_date, status, usage_count)
                    VALUES (?, ?, ?, ?, ?, ?, ?, 0)
                ");
                $stmt->execute([$user_id, $plan_name, $price, $max_usage, $start_date, $end_date, $status]);
                $message = 'Subscription created successfully';
            }
            
            echo json_encode([
                'success' => true,
                'message' => $message
            ]);
            break;
        
        case 'cancel_subscription':
            $id = $_POST['id'];
            $stmt = $pdo->prepare("UPDATE subscriptions SET status = 'cancelled' WHERE id = ?");
            $stmt->execute([$id]);
            
            echo json_encode([
                'success' => true,
                'message' => 'Subscription cancelled successfully'
            ]);
            break;
        
        case 'delete_subscription':
            $id = $_POST['id'];
            $stmt = $pdo->prepare("DELETE FROM subscriptions WHERE id = ?");
            $stmt->execute([$id]);
            
            echo json_encode([
                'success' => true,
                'message' => 'Subscription deleted successfully'
            ]);
            break;
        
        case 'get_plans':
            $stmt = $pdo->prepare("
                SELECT 
                    so.id,
                    so.option_name as plan_name,
                    so.option_value as plan_type,
                    s.price + so.price_modifier as price,
                    s.description,
                    so.price_modifier
                FROM service_options so
                JOIN services s ON so.service_id = s.id
                WHERE s.category = 'subscription' 
                AND so.option_type = 'subscription_type'
                ORDER BY so.option_value ASC
            ");
            $stmt->execute();
            $plans = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($plans as &$plan) {
                $plan['max_usage'] = ($plan['plan_type'] == 'weekly') ? 5 : 10;
                $plan['duration_days'] = ($plan['plan_type'] == 'weekly') ? 7 : 30;
                $plan['features'] = "Free pickup & delivery\n" . $plan['max_usage'] . " items per " . $plan['plan_type'] . "\nStandard service";
            }
            
            echo json_encode([
                'success' => true,
                'plans' => $plans
            ]);
            break;
        
        case 'get_plan':
            $id = $_GET['id'] ?? 0;
            $stmt = $pdo->prepare("
                SELECT 
                    so.id,
                    so.option_name as plan_name,
                    so.option_value as plan_type,
                    s.price as base_price,
                    so.price_modifier,
                    s.price + so.price_modifier as price,
                    s.description
                FROM service_options so
                JOIN services s ON so.service_id = s.id
                WHERE so.id = ? AND so.option_type = 'subscription_type'
            ");
            $stmt->execute([$id]);
            $plan = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($plan) {
                $plan['max_usage'] = ($plan['plan_type'] == 'weekly') ? 5 : 10;
                $plan['duration_days'] = ($plan['plan_type'] == 'weekly') ? 7 : 30;
                
                echo json_encode([
                    'success' => true,
                    'plan' => $plan
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Plan not found'
                ]);
            }
            break;
        
        case 'save_plan':
            $id = $_POST['id'] ?? null;
            $plan_name = $_POST['plan_name'];
            $price_modifier = $_POST['price_modifier'];
            
            if ($id) {
                $stmt = $pdo->prepare("
                    UPDATE service_options 
                    SET option_name = ?, price_modifier = ?
                    WHERE id = ? AND option_type = 'subscription_type'
                ");
                $stmt->execute([$plan_name, $price_modifier, $id]);
                
                echo json_encode([
                    'success' => true,
                    'message' => 'Plan updated successfully'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Plan ID is required'
                ]);
            }
            break;
        
        case 'update_base_price':
            $price = $_POST['price'];
            
            $stmt = $pdo->prepare("UPDATE services SET price = ? WHERE category = 'subscription'");
            $stmt->execute([$price]);
            
            echo json_encode([
                'success' => true,
                'message' => 'Base price updated successfully'
            ]);
            break;
        
        case 'get_customers':
            $stmt = $pdo->prepare("
                SELECT id, name, email 
                FROM users 
                WHERE role != 'admin'
                ORDER BY name ASC
            ");
            $stmt->execute();
            $customers = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'customers' => $customers
            ]);
            break;
        
        case 'get_activity':
            $stmt = $pdo->prepare("
                SELECT s.*, u.name as customer_name, 
                       CASE 
                           WHEN s.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 'New'
                           WHEN s.status = 'cancelled' THEN 'Cancelled'
                           WHEN s.end_date < CURDATE() THEN 'Expired'
                           ELSE 'Active'
                       END as action
                FROM subscriptions s
                LEFT JOIN users u ON s.user_id = u.id
                ORDER BY s.created_at DESC
                LIMIT 20
            ");
            $stmt->execute();
            $activity = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'activity' => $activity
            ]);
            break;
        
        default:
            echo json_encode([
                'success' => false,
                'message' => 'Invalid action'
            ]);
    }
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
