<?php
// api/users/index.php

require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../helpers/response.php';
require_once '../../helpers/request.php';
require_once '../../helpers/auth.php';

$method = getRequestMethod();

if ($method === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Require admin access for all user operations
$user = requireAdmin();

// GET - List users
if ($method === 'GET') {
    $search = isset($_GET['search']) ? $_GET['search'] : null;
    $role_id = isset($_GET['role_id']) ? intval($_GET['role_id']) : null;
    $status = isset($_GET['status']) ? $_GET['status'] : null;
    $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50;
    $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;
    
    try {
        $sql = "SELECT u.id, u.name, u.email, u.role_id, u.status, u.created_at, r.name as role_name
                FROM users u
                LEFT JOIN roles r ON r.id = u.role_id
                WHERE 1=1";
        $params = [];
        
        if ($search) {
            $sql .= " AND (u.name LIKE :search OR u.email LIKE :search)";
            $params[':search'] = "%{$search}%";
        }
        
        if ($role_id) {
            $sql .= " AND u.role_id = :role_id";
            $params[':role_id'] = $role_id;
        }
        
        if ($status) {
            $sql .= " AND u.status = :status";
            $params[':status'] = $status;
        }
        
        $sql .= " ORDER BY u.created_at DESC LIMIT :limit OFFSET :offset";
        $params[':limit'] = $limit;
        $params[':offset'] = $offset;
        
        $stmt = $pdo->prepare($sql);
        foreach ($params as $key => &$val) {
            if ($key === ':limit' || $key === ':offset') {
                $stmt->bindParam($key, $val, PDO::PARAM_INT);
            } else {
                $stmt->bindParam($key, $val);
            }
        }
        $stmt->execute();
        
        $users = $stmt->fetchAll();
        
        // Get total count
        $countSql = "SELECT COUNT(*) FROM users WHERE 1=1";
        $countParams = [];
        if ($search) {
            $countSql .= " AND (name LIKE :search OR email LIKE :search)";
            $countParams[':search'] = "%{$search}%";
        }
        if ($role_id) {
            $countSql .= " AND role_id = :role_id";
            $countParams[':role_id'] = $role_id;
        }
        if ($status) {
            $countSql .= " AND status = :status";
            $countParams[':status'] = $status;
        }
        
        $countStmt = $pdo->prepare($countSql);
        foreach ($countParams as $key => $val) {
            $countStmt->bindValue($key, $val);
        }
        $countStmt->execute();
        $total = $countStmt->fetchColumn();
        
        sendSuccess([
            'data' => $users,
            'pagination' => [
                'total' => intval($total),
                'limit' => $limit,
                'offset' => $offset
            ]
        ]);
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
    
// POST - Create new user
} elseif ($method === 'POST') {
    $data = getRequestData();
    
    validateRequiredFields($data, ['name', 'email', 'password', 'role_id']);
    
    try {
        // Check if email exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = :email");
        $stmt->execute([':email' => $data['email']]);
        if ($stmt->fetch()) {
            sendError('Email already exists', 400);
        }
        
        // Hash password
        $hashed_password = password_hash($data['password'], PASSWORD_DEFAULT);
        
        // Generate email verification token
        $verification_token = bin2hex(random_bytes(32));
        
        // Create user
        $stmt = $pdo->prepare("
            INSERT INTO users (name, email, password, role_id, status) 
            VALUES (:name, :email, :password, :role_id, 'pending')
        ");
        
        $stmt->execute([
            ':name' => $data['name'],
            ':email' => $data['email'],
            ':password' => $hashed_password,
            ':role_id' => $data['role_id']
        ]);
        
        $user_id = $pdo->lastInsertId();
        
        // Store verification token (you'll need a table for this)
        $stmt = $pdo->prepare("
            INSERT INTO email_verifications (user_id, token, expires_at) 
            VALUES (:user_id, :token, DATE_ADD(NOW(), INTERVAL 24 HOUR))
        ");
        $stmt->execute([
            ':user_id' => $user_id,
            ':token' => $verification_token
        ]);
        
        // Mock email sending (log to file)
        $verification_link = "http://localhost/mypodcast/api/auth/verify-email.php?token=" . $verification_token;
        
        $email_log = "========================================\n";
        $email_log .= "TO: " . $data['email'] . "\n";
        $email_log .= "SUBJECT: Verify Your Email Address\n";
        $email_log .= "========================================\n";
        $email_log .= "Hello " . $data['name'] . ",\n\n";
        $email_log .= "Please verify your email address by clicking the link below:\n\n";
        $email_log .= $verification_link . "\n\n";
        $email_log .= "This link expires in 24 hours.\n\n";
        $email_log .= "If you did not create an account, please ignore this email.\n";
        $email_log .= "========================================\n\n";
        
        // Save to log file
        $log_file = __DIR__ . '/../../logs/emails.log';
        if (!file_exists(dirname($log_file))) {
            mkdir(dirname($log_file), 0777, true);
        }
        file_put_contents($log_file, $email_log, FILE_APPEND);
        
        sendSuccess([
            'id' => $user_id,
            'name' => $data['name'],
            'email' => $data['email'],
            'role_id' => $data['role_id'],
            'status' => 'pending',
            'verification_token' => $verification_token // For testing only
        ], 'User created. Verification email sent (mock). Check logs/emails.log');
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
    
} else {
    sendError('Method not allowed', 405);
}
?>