<?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' => '',
    'users' => [],
    'designations' => [],
    'kyc_approvals' => [],
    'total_pages' => 1,
    'page' => 1
];

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

$currentUser = getCurrentUser();
$tab = $_GET['tab'] ?? 'users';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Fetch all designations for options dropdown
try {
    $response['designations'] = $pdo->query("SELECT id, title FROM designations ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (PDOException $e) { }

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

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

    if (isset($_POST['submit_add'])) {
        $username = trim($_POST['username'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $role = $_POST['role'] ?? 'user';
        $status = $_POST['status'] ?? 'active';
        $employee_code = trim($_POST['employee_code'] ?? '');
        $designation_id = isset($_POST['designation_id']) && $_POST['designation_id'] !== '' ? (int)$_POST['designation_id'] : null;
        $referrer_username = trim($_POST['referrer_username'] ?? '');

        if (empty($username) || empty($email) || empty($password)) {
            $response['message'] = "Please fill in all required fields.";
        } else {
            try {
                $check = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ? OR email = ?");
                $check->execute([$username, $email]);
                if ($check->fetchColumn() > 0) {
                    $response['message'] = "Username or Email already exists.";
                } else {
                    $referrer_id = null;
                    $parent_id = null;

                    if (!empty($referrer_username)) {
                        $stmt_ref = $pdo->prepare("SELECT id, designation_id FROM users WHERE username = ? OR employee_code = ?");
                        $stmt_ref->execute([$referrer_username, $referrer_username]);
                        $referrer = $stmt_ref->fetch();
                        if (!$referrer) {
                            $response['message'] = "The referrer/sponsor username or employee code does not exist.";
                            echo json_encode($response);
                            exit();
                        }
                        $referrer_id = $referrer['id'];

                        // Fetch matrix config of the sponsor to calculate parent with spillover
                        $m_width = 4;
                        $m_depth = 4;
                        if ($referrer['designation_id']) {
                            $stmt_m = $pdo->prepare("SELECT matrix_width, matrix_depth FROM designations WHERE id = ?");
                            $stmt_m->execute([$referrer['designation_id']]);
                            $des = $stmt_m->fetch();
                            if ($des) {
                                $m_width = (int)$des['matrix_width'];
                                $m_depth = (int)$des['matrix_depth'];
                            }
                        }

                        $parent_id = findMatrixPlacement($referrer_id, $m_width, $m_depth);
                    }

                    $final_emp_code = $employee_code;
                    if (empty($final_emp_code)) {
                        // Use consistent employee code generation (#26)
                        $settings = getSystemSettings();
                        $prefix = $settings['emp_code_prefix'] ?? 'REPL';
                        $length = (int)($settings['emp_code_length'] ?? 15);
                        $final_emp_code = generateEmployeeCode($prefix, $length);
                    }

                    $hashedPass = password_hash($password, PASSWORD_DEFAULT);
                    $insert = $pdo->prepare("INSERT INTO users (username, email, password, role, status, employee_code, designation_id, referrer_id, parent_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $insert->execute([$username, $email, $hashedPass, $role, $status, $final_emp_code, $designation_id, $referrer_id, $parent_id]);
                    $new_user_id = $pdo->lastInsertId();
                    require_once __DIR__ . '/../../includes/bonus_helper.php';
                    awardSignupAndReferralBonuses($new_user_id, $referrer_id);
                    
                    $response['success'] = true;
                    $response['message'] = "User '$username' created successfully.";
                    logAuditEvent('admin_create_user', 'user', $new_user_id, "Created user: $username ($email)");
                }
            } catch (PDOException $e) {
                error_log("Admin add user error: " . $e->getMessage());
                $response['message'] = "An unexpected error occurred. Please try again later.";
            }
        }
    } elseif (isset($_POST['submit_edit'])) {
        $editId = (int)$_POST['edit_id'];
        $username = trim($_POST['username'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $role = $_POST['role'] ?? 'user';
        $status = $_POST['status'] ?? 'active';
        $employee_code = trim($_POST['employee_code'] ?? '');
        $designation_id = isset($_POST['designation_id']) && $_POST['designation_id'] !== '' ? (int)$_POST['designation_id'] : null;

        if (empty($username) || empty($email)) {
            $response['message'] = "Username and email are required.";
        } else {
            try {
                // Uniqueness check for email and username (#13)
                $check_dup = $pdo->prepare("SELECT COUNT(*) FROM users WHERE (username = ? OR email = ?) AND id != ?");
                $check_dup->execute([$username, $email, $editId]);
                if ($check_dup->fetchColumn() > 0) {
                    $response['message'] = "Username or Email already exists for another user.";
                } else {
                    // Check employee_code uniqueness if provided
                    if (!empty($employee_code)) {
                        $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ? AND id != ?");
                        $check_code->execute([$employee_code, $editId]);
                        if ($check_code->fetchColumn() > 0) {
                            $response['message'] = "This employee code is already in use by another user.";
                            echo json_encode($response);
                            exit();
                        }
                    }
                    $stmt = $pdo->prepare("UPDATE users SET username = ?, email = ?, role = ?, status = ?, employee_code = ?, designation_id = ? WHERE id = ?");
                    $stmt->execute([$username, $email, $role, $status, $employee_code, $designation_id, $editId]);
                    
                    if (!empty($_POST['password'])) {
                        $hashed = password_hash($_POST['password'], PASSWORD_DEFAULT);
                        $pdo->prepare("UPDATE users SET password = ? WHERE id = ?")->execute([$hashed, $editId]);
                    }

                    $response['success'] = true;
                    $response['message'] = "User updated successfully.";
                    logAuditEvent('admin_edit_user', 'user', $editId, "Updated user: $username ($email)");
                }
            } catch (PDOException $e) {
                error_log("Admin edit user error: " . $e->getMessage());
                $response['message'] = "An unexpected error occurred. Please try again later.";
            }
        }
    } elseif ($action === 'delete') {
        $deleteId = (int)($_POST['id'] ?? 0);
        if ($deleteId === $currentUser['id']) {
            $response['message'] = "You cannot delete your own account.";
        } else {
            try {
                // Check for active dependencies before deletion (#10)
                $stmt_pending = $pdo->prepare("SELECT COUNT(*) FROM payouts WHERE user_id = ? AND status = 'pending'");
                $stmt_pending->execute([$deleteId]);
                $pending_payouts = (int)$stmt_pending->fetchColumn();

                $stmt_children = $pdo->prepare("SELECT COUNT(*) FROM users WHERE referrer_id = ? OR parent_id = ?");
                $stmt_children->execute([$deleteId, $deleteId]);
                $child_count = (int)$stmt_children->fetchColumn();

                if ($pending_payouts > 0) {
                    $response['message'] = "Cannot delete user: they have $pending_payouts pending payout(s). Please resolve them first.";
                } elseif ($child_count > 0) {
                    $response['message'] = "Cannot delete user: they have $child_count team member(s) in the network. Consider deactivating instead.";
                } else {
                    // Soft-delete: deactivate instead of hard-delete to preserve data integrity
                    $pdo->prepare("UPDATE users SET status = 'deleted', email = CONCAT(email, '_deleted_', id) WHERE id = ?")->execute([$deleteId]);
                    $response['success'] = true;
                    $response['message'] = "User has been deactivated and marked as deleted.";
                    logAuditEvent('admin_delete_user', 'user', $deleteId, 'Soft-deleted user');
                }
            } catch (PDOException $e) {
                $response['message'] = "Delete failed.";
            }
        }
    } elseif (in_array($action, ['approve_doc1', 'reject_doc1', 'approve_doc2', 'reject_doc2'])) {
        $kycId = (int)($_POST['kyc_id'] ?? 0);
        try {
            $stmt_get_user = $pdo->prepare("SELECT user_id FROM kyc_records WHERE id = ?");
            $stmt_get_user->execute([$kycId]);
            $target_user_id = $stmt_get_user->fetchColumn();

            require_once __DIR__ . '/../../includes/notification_helper.php';

            if ($action === 'approve_doc1') {
                $pdo->prepare("UPDATE kyc_records SET doc1_status = 'approved', updated_at = CURRENT_TIMESTAMP WHERE id = ?")->execute([$kycId]);
                sendMultichannelNotification($target_user_id, 'kyc_status', ['status' => 'Photo ID Approved']);
                $response['message'] = "Photo ID approved.";
            } elseif ($action === 'reject_doc1') {
                $pdo->prepare("UPDATE kyc_records SET doc1_status = 'rejected', updated_at = CURRENT_TIMESTAMP WHERE id = ?")->execute([$kycId]);
                sendMultichannelNotification($target_user_id, 'kyc_status', ['status' => 'Photo ID Rejected']);
                $response['message'] = "Photo ID rejected.";
            } elseif ($action === 'approve_doc2') {
                $pdo->prepare("UPDATE kyc_records SET doc2_status = 'approved', updated_at = CURRENT_TIMESTAMP WHERE id = ?")->execute([$kycId]);
                sendMultichannelNotification($target_user_id, 'kyc_status', ['status' => 'Address Proof Approved']);
                $response['message'] = "Address Proof approved.";
            } elseif ($action === 'reject_doc2') {
                $pdo->prepare("UPDATE kyc_records SET doc2_status = 'rejected', updated_at = CURRENT_TIMESTAMP WHERE id = ?")->execute([$kycId]);
                sendMultichannelNotification($target_user_id, 'kyc_status', ['status' => 'Address Proof Rejected']);
                $response['message'] = "Address Proof rejected.";
            }
            $response['success'] = true;
        } catch (PDOException $e) {
            $response['message'] = "Action failed.";
        }
    }
} else {
    // GET requests
    try {
        if ($tab === 'users') {
            $search = trim($_GET['search'] ?? '');
            $status = trim($_GET['status'] ?? '');

            $count_q = "SELECT COUNT(*) FROM users u WHERE 1=1";
            $data_q = "
                SELECT u.*, d.title as designation_title, r.username as referrer_username, p.username as parent_username 
                FROM users u 
                LEFT JOIN designations d ON u.designation_id = d.id 
                LEFT JOIN users r ON u.referrer_id = r.id 
                LEFT JOIN users p ON u.parent_id = p.id
                WHERE 1=1
            ";
            $params = [];

            if ($search !== '') {
                $count_q .= " AND (u.username ILIKE ? OR u.email ILIKE ? OR u.employee_code ILIKE ?)";
                $data_q .= " AND (u.username ILIKE ? OR u.email ILIKE ? OR u.employee_code ILIKE ?)";
                $params[] = "%$search%";
                $params[] = "%$search%";
                $params[] = "%$search%";
            }
            if ($status !== '') {
                $count_q .= " AND u.status = ?";
                $data_q .= " AND u.status = ?";
                $params[] = $status;
            }

            $stmt_c = $pdo->prepare($count_q);
            $stmt_c->execute($params);
            $total = (int)$stmt_c->fetchColumn();

            $data_q .= " ORDER BY u.id DESC LIMIT ? OFFSET ?";
            $stmt_d = $pdo->prepare($data_q);
            foreach ($params as $idx => $val) {
                $stmt_d->bindValue($idx + 1, $val);
            }
            $stmt_d->bindValue(count($params) + 1, $limit, PDO::PARAM_INT);
            $stmt_d->bindValue(count($params) + 2, $offset, PDO::PARAM_INT);
            $stmt_d->execute();

            $response['users'] = $stmt_d->fetchAll(PDO::FETCH_ASSOC) ?: [];
            $response['total_pages'] = max(1, ceil($total / $limit));
            $response['page'] = $page;
            $response['success'] = true;
        } elseif ($tab === 'kyc_approvals') {
            $count_q = "SELECT COUNT(*) FROM kyc_records";
            $data_q = "
                SELECT k.*, u.username, u.email 
                FROM kyc_records k 
                JOIN users u ON k.user_id = u.id 
                ORDER BY k.updated_at DESC LIMIT ? OFFSET ?
            ";
            
            $total = (int)$pdo->query($count_q)->fetchColumn();
            
            $stmt_d = $pdo->prepare($data_q);
            $stmt_d->bindValue(1, $limit, PDO::PARAM_INT);
            $stmt_d->bindValue(2, $offset, PDO::PARAM_INT);
            $stmt_d->execute();

            $response['kyc_approvals'] = $stmt_d->fetchAll(PDO::FETCH_ASSOC) ?: [];
            $response['total_pages'] = max(1, ceil($total / $limit));
            $response['page'] = $page;
            $response['success'] = true;
        }
    } catch (PDOException $e) {
        $response['message'] = "Database error.";
    }
}

echo json_encode($response);
