<?php
// ════════════════════════════════════════════════════════
// CHANGE PASSWORD API
// Place in: Triangle_Tree_Life_Number/api/auth/change-password.php
// ════════════════════════════════════════════════════════

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

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

require_once '../config/db.php';
require_once '../config/helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit();
}

try {
    $input = json_decode(file_get_contents('php://input'), true);
    $changeToken = $input['changeToken'] ?? '';
    $newPassword = $input['newPassword'] ?? '';

    // Validate input
    if (empty($changeToken) || empty($newPassword)) {
        http_response_code(400);
        echo json_encode(['error' => 'Token and new password required']);
        exit();
    }

    // Validate password strength
    if (strlen($newPassword) < 8) {
        http_response_code(400);
        echo json_encode(['error' => 'Password must be at least 8 characters']);
        exit();
    }

    // Find user by change token
    $stmt = $pdo->prepare("
        SELECT * FROM users 
        WHERE session_token = ? AND must_change_password = 1
    ");
    $stmt->execute([$changeToken]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired token']);
        exit();
    }

    // Update password and clear temp flags
    $hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);
    $newSessionToken = bin2hex(random_bytes(16));

    $stmt = $pdo->prepare("
        UPDATE users 
        SET password = ?, 
            temp_password = 0, 
            must_change_password = 0,
            session_token = ?,
            updated_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([$hashedPassword, $newSessionToken, $user['id']]);

    // Generate JWT for automatic login
    $jwtSecret = getenv('JWT_SECRET') ?: 'default_secret_change_this';
    $payload = [
        'userId' => $user['id'],
        'email' => $user['email'],
        'role' => $user['role'],
        'st' => $newSessionToken
    ];
    
    $accessToken = createJWT($payload, $jwtSecret, '7d');

    echo json_encode([
        'success' => true,
        'accessToken' => $accessToken,
        'message' => 'Password changed successfully',
        'user' => [
            'id' => $user['id'],
            'email' => $user['email'],
            'role' => $user['role'],
            'emailVerified' => (bool)$user['email_verified'],
            'phoneVerified' => (bool)$user['phone_verified'],
            'registeredBy' => $user['registered_by']
        ]
    ]);

} catch (Exception $e) {
    error_log('Change password error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'error' => 'Password change failed',
        'details' => $e->getMessage()
    ]);
}
?>
