<?php
// ════════════════════════════════════════════════════════
// USER MANAGEMENT API
// Place in: Triangle_Tree_Life_Number/api/users.php
// ════════════════════════════════════════════════════════

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once 'config/db.php';       // Database in config/
require_once 'config/helpers.php';  // Helpers in config/
require_once 'config/smtp_mailer.php'; // SMTP email sender

// Get authorization token
$headers = getallheaders();
$token = isset($headers['Authorization']) ? str_replace('Bearer ', '', $headers['Authorization']) : null;

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized - No token provided']);
    exit();
}

// Verify token and get current user
$currentUser = verifyToken($token);  // Returns user object with id, email, role
if (!$currentUser) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized - Invalid token']);
    exit();
}

// Route handling
$method = $_SERVER['REQUEST_METHOD'];
$path = $_SERVER['REQUEST_URI'];
$pathParts = explode('/', trim($path, '/'));
$userId = isset($pathParts[count($pathParts) - 1]) && is_numeric($pathParts[count($pathParts) - 1]) 
    ? intval($pathParts[count($pathParts) - 1]) 
    : null;

// ════════════════════════════════════════════════════════
// GET /api/users - Get all users (admin+ only)
// ════════════════════════════════════════════════════════
if ($method === 'GET' && !$userId) {
    if (!in_array($currentUser['role'], ['super_admin', 'admin'])) {
        http_response_code(403);
        echo json_encode(['error' => 'Forbidden - Admin access required']);
        exit();
    }
    
    $stmt = $pdo->query("
        SELECT id, name, email, phone, role, is_active, created_at 
        FROM users 
        ORDER BY created_at DESC
    ");
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode($users);
    exit();
}

// ════════════════════════════════════════════════════════
// POST /api/users/register - Register new user (super_admin only)
// ════════════════════════════════════════════════════════
if ($method === 'POST' && strpos($path, '/register') !== false) {
    try {
        // Debug: Check current user
        if (!isset($currentUser) || !$currentUser) {
            http_response_code(401);
            echo json_encode(['error' => 'DEBUG: currentUser is not set or empty']);
            exit();
        }
        
        if (!isset($currentUser['role'])) {
            http_response_code(500);
            echo json_encode(['error' => 'DEBUG: currentUser exists but has no role', 'currentUser' => $currentUser]);
            exit();
        }
        
        if ($currentUser['role'] !== 'super_admin') {
            http_response_code(403);
            echo json_encode(['error' => 'Forbidden - Super Admin access required', 'yourRole' => $currentUser['role']]);
            exit();
        }
        
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input) {
            http_response_code(400);
            echo json_encode(['error' => 'DEBUG: No JSON input received']);
            exit();
        }
        
        $email = $input['email'] ?? '';
        $password = $input['password'] ?? '';
        $role = $input['role'] ?? 'user';
        
        if (empty($email) || empty($password)) {
            http_response_code(400);
            echo json_encode(['error' => 'Email and password required', 'received' => ['email' => $email ? 'yes' : 'no', 'password' => $password ? 'yes' : 'no']]);
            exit();
        }
        
        // Check if email exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            http_response_code(400);
            echo json_encode(['error' => 'Email already exists']);
            exit();
        }
        
        // Hash password
        $passwordHash = password_hash($password, PASSWORD_DEFAULT);
        
        // Insert user (with empty name and NULL phone)
        $stmt = $pdo->prepare("
            INSERT INTO users (name, email, phone, password, role, is_active, created_at) 
            VALUES (?, ?, ?, ?, ?, 1, NOW())
        ");
        $result = $stmt->execute(['', $email, null, $passwordHash, $role]);
        
        if (!$result) {
            http_response_code(500);
            echo json_encode(['error' => 'DEBUG: Insert failed', 'errorInfo' => $stmt->errorInfo()]);
            exit();
        }
        
        $userId = $pdo->lastInsertId();
        
        // Send welcome email with temporary password
        $subject = 'Welcome to Numerology System - Your Account Details';
        $message = "
<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
</head>
<body style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;'>
    <div style='background: linear-gradient(135deg, #2563a8, #1e4a7a); padding: 30px; border-radius: 10px 10px 0 0; text-align: center;'>
        <h1 style='color: #fff; margin: 0; font-size: 28px; font-family: Cormorant Garamond, serif;'>Numerology</h1>
        <p style='color: rgba(255,255,255,0.9); margin: 5px 0 0; font-size: 12px; letter-spacing: 0.15em;'>SACRED MATHEMATICS</p>
    </div>
    
    <div style='background: #f8f9fa; padding: 30px; border-radius: 0 0 10px 10px;'>
        <h2 style='color: #1a2530; font-size: 20px; margin-top: 0;'>Welcome to Numerology System!</h2>
        
        <p style='color: #4a5568; line-height: 1.6;'>Your account has been created successfully. Below are your login credentials:</p>
        
        <div style='background: white; border-left: 4px solid #2563a8; padding: 20px; margin: 20px 0; border-radius: 5px;'>
            <p style='margin: 0 0 10px; color: #1a2530;'><strong>Email:</strong> " . htmlspecialchars($email) . "</p>
            <p style='margin: 0; color: #1a2530;'><strong>Temporary Password:</strong> <code style='background: #f0f4f8; padding: 5px 10px; border-radius: 5px; font-size: 16px; color: #2563a8;'>" . htmlspecialchars($password) . "</code></p>
        </div>
        
        <div style='background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 5px;'>
            <p style='margin: 0; color: #856404; font-size: 14px;'><strong>⚠️ Important:</strong> Please change your password after your first login for security.</p>
        </div>
        
        <p style='color: #4a5568; line-height: 1.6;'>Login here: <a href='https://decode.com.my/Triangle_Tree_Life_Number/test_login.html' style='color: #2563a8;'>https://decode.com.my/Triangle_Tree_Life_Number/test_login.html</a></p>
        
        <p style='color: #6b7280; font-size: 13px; margin-top: 30px; padding-top: 20px; border-top: 1px solid #e5e7eb;'>If you did not request this account, please contact your system administrator.</p>
    </div>
</body>
</html>
        ";
        
        // Send welcome email via authenticated SMTP
        $mailResult = sendSmtpMail($email, '', $subject, $message);
        $emailSent  = $mailResult['ok'];
        
        echo json_encode([
            'success' => true, 
            'id' => $userId, 
            'message' => 'User registered successfully',
            'emailSent' => $emailSent,
            'note' => $emailSent
                ? 'Welcome email sent'
                : ('User created but email failed: ' . $mailResult['error'])
        ]);
        exit();
        
    } catch(PDOException $e) {
        http_response_code(500);
        $errorInfo = $e->errorInfo ?? [];
        echo json_encode([
            'error' => 'Database error', 
            'details' => $e->getMessage(),
            'code' => $e->getCode(),
            'sqlstate' => $errorInfo[0] ?? '',
            'driver_code' => $errorInfo[1] ?? '',
            'driver_message' => $errorInfo[2] ?? '',
            'query_hint' => 'Check if all required fields have values or if email already exists'
        ]);
        exit();
    } catch(Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'General error', 'details' => $e->getMessage()]);
        exit();
    }
}

// ════════════════════════════════════════════════════════
// PUT /api/users/:id - Update user (with permission check)
// ════════════════════════════════════════════════════════
if ($method === 'PUT' && $userId) {
    $input = json_decode(file_get_contents('php://input'), true);
    $newRole = $input['role'] ?? null;
    $isActive = isset($input['is_active']) ? intval($input['is_active']) : null;
    
    // Get target user
    $stmt = $pdo->prepare("SELECT role FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $targetUser = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$targetUser) {
        http_response_code(404);
        echo json_encode(['error' => 'User not found']);
        exit();
    }
    
    // Permission check
    $canEdit = false;
    if ($currentUser['role'] === 'super_admin') {
        $canEdit = true;
    } elseif ($currentUser['role'] === 'admin') {
        // Admin can only edit user and super_user
        if (in_array($targetUser['role'], ['user', 'super_user'])) {
            $canEdit = true;
            // Admin cannot set role to admin or super_admin
            if (in_array($newRole, ['admin', 'super_admin'])) {
                http_response_code(403);
                echo json_encode(['error' => 'Admins cannot promote to admin or super_admin']);
                exit();
            }
        }
    }
    
    if (!$canEdit) {
        http_response_code(403);
        echo json_encode(['error' => 'Forbidden - Insufficient permissions']);
        exit();
    }
    
    // Update user
    $updates = [];
    $params = [];
    
    if ($newRole) {
        $updates[] = "role = ?";
        $params[] = $newRole;
    }
    if ($isActive !== null) {
        $updates[] = "is_active = ?";
        $params[] = $isActive;
    }
    
    $updates[] = "updated_at = NOW()";
    $params[] = $userId;
    
    $sql = "UPDATE users SET " . implode(', ', $updates) . " WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    
    echo json_encode(['success' => true]);
    exit();
}

// ════════════════════════════════════════════════════════
// DELETE /api/users/:id - Delete user (super_admin only)
// ════════════════════════════════════════════════════════
if ($method === 'DELETE' && $userId) {
    if ($currentUser['role'] !== 'super_admin') {
        http_response_code(403);
        echo json_encode(['error' => 'Forbidden - Super Admin access required']);
        exit();
    }
    
    // Cannot delete self
    if ($userId == $currentUser['id']) {
        http_response_code(400);
        echo json_encode(['error' => 'Cannot delete yourself']);
        exit();
    }
    
    $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    
    echo json_encode(['success' => true]);
    exit();
}

http_response_code(404);
echo json_encode(['error' => 'Endpoint not found']);
?>
