<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

$response = [
    'success' => false,
    'message' => '',
    'designations' => [],
    'events' => []
];

if (!isLoggedIn() || getCurrentUser()['role'] !== 'admin') {
    $response['message'] = "Unauthorized.";
    echo json_encode($response);
    exit();
}

try {
    $response['events'] = $pdo->query("SELECT id, title FROM events ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC) ?: [];
    $response['designations'] = $pdo->query("SELECT * FROM designations ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC) ?: [];
    $response['success'] = true;
} catch (PDOException $e) { }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $response['success'] = false;
        $response['message'] = "Security check failed (CSRF).";
        echo json_encode($response);
        exit();
    }

    $action = $_POST['action'] ?? '';

    if ($action === 'delete') {
        $deleteId = (int)($_POST['id'] ?? 0);
        try {
            $pdo->prepare("DELETE FROM designations WHERE id = ?")->execute([$deleteId]);
            $response['success'] = true;
            $response['message'] = "Designation deleted successfully.";
        } catch (PDOException $e) {
            $response['success'] = false;
            $response['message'] = "Failed to delete designation (it may be assigned to active users).";
        }
    } elseif (isset($_POST['submit_desig'])) {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $is_default = isset($_POST['is_default']) ? 1 : 0;
        $matrix_width = (int)($_POST['matrix_width'] ?? 4);
        $matrix_depth = (int)($_POST['matrix_depth'] ?? 4);
        $level_commissions = trim($_POST['level_commissions'] ?? '');
        $criteria_direct_referrals = (int)($_POST['criteria_direct_referrals'] ?? 0);
        $criteria_team_size = (int)($_POST['criteria_team_size'] ?? 0);
        $criteria_min_payout = (float)($_POST['criteria_min_payout'] ?? 0.00);
        $criteria_max_earning_cap = (float)($_POST['criteria_max_earning_cap'] ?? 0.00);
        $criteria_min_duration_months = (int)($_POST['criteria_min_duration_months'] ?? 0);
        $allow_wallet_payment = isset($_POST['allow_wallet_payment']) ? 1 : 0;
        
        $sel_events = $_POST['accessible_event_ids'] ?? [];
        // Support array check
        if (!is_array($sel_events)) {
            $sel_events = $sel_events ? explode(',', $sel_events) : [];
        }
        $accessible_event_ids = implode(',', array_map('intval', $sel_events));

        $commissions_arr = array_filter(array_map('trim', explode(',', $level_commissions)));
        $commissions_sum = 0;
        $error = '';
        foreach ($commissions_arr as $c) {
            if (!is_numeric($c)) {
                $error = "Commissions must be comma-separated numbers.";
                break;
            }
            $commissions_sum += (float)$c;
        }

        if (empty($title)) {
            $error = "Designation Title is required.";
        } elseif ($commissions_sum > 50) {
            $error = "The sum of level commissions cannot exceed 50%.";
        } elseif (count($commissions_arr) > $matrix_depth) {
            $error = "You cannot configure more commission levels than the matrix depth ($matrix_depth).";
        }

        if (!empty($error)) {
            $response['success'] = false;
            $response['message'] = $error;
        } else {
            try {
                $pdo->beginTransaction();

                if ($is_default) {
                    $pdo->exec("UPDATE designations SET is_default = FALSE WHERE is_default = TRUE");
                }

                if ($id > 0) {
                    $upd_stmt = $pdo->prepare("
                        UPDATE designations 
                        SET title = ?, description = ?, is_default = ?, matrix_width = ?, matrix_depth = ?, level_commissions = ?, 
                            criteria_direct_referrals = ?, criteria_team_size = ?, criteria_min_payout = ?, 
                            criteria_max_earning_cap = ?, criteria_min_duration_months = ?, accessible_event_ids = ?,
                            allow_wallet_payment = ?
                        WHERE id = ?
                    ");
                    $upd_stmt->execute([
                        $title, $description, $is_default ? 'true' : 'false', $matrix_width, $matrix_depth, implode(',', $commissions_arr),
                        $criteria_direct_referrals, $criteria_team_size, $criteria_min_payout, 
                        $criteria_max_earning_cap, $criteria_min_duration_months, $accessible_event_ids, $allow_wallet_payment ? 'true' : 'false', $id
                    ]);
                    $response['message'] = "Designation updated successfully.";
                } else {
                    $ins_stmt = $pdo->prepare("
                        INSERT INTO designations 
                        (title, description, is_default, matrix_width, matrix_depth, level_commissions, criteria_direct_referrals, criteria_team_size, criteria_min_payout, criteria_max_earning_cap, criteria_min_duration_months, accessible_event_ids, allow_wallet_payment) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    $ins_stmt->execute([
                        $title, $description, $is_default ? 'true' : 'false', $matrix_width, $matrix_depth, implode(',', $commissions_arr),
                        $criteria_direct_referrals, $criteria_team_size, $criteria_min_payout, 
                        $criteria_max_earning_cap, $criteria_min_duration_months, $accessible_event_ids, $allow_wallet_payment ? 'true' : 'false'
                    ]);
                    $response['message'] = "Designation created successfully.";
                }
                
                $pdo->commit();
                $response['success'] = true;
            } catch (PDOException $e) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                error_log("Designation save error: " . $e->getMessage());
                $response['success'] = false;
                $response['message'] = "Failed to save designation. Please try again.";
            }
        }
    }
}

echo json_encode($response);
