<?php
/**
 * Change Password API
 * Endpoint: /admin/adminapi/change_password.php
 */
require_once(__DIR__ . '/includes/db.php');
require_once(__DIR__ . '/includes/auth.php');
require_once(__DIR__ . '/includes/activity_logger.php');

header('Content-Type: application/json');

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

// Require valid auth token
$adminId = requireAuth();

try {
    // Get input
    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input) {
        $input = $_POST;
    }

    $currentPassword = isset($input['current_password']) ? trim($input['current_password']) : '';
    $newPassword = isset($input['new_password']) ? trim($input['new_password']) : '';
    $confirmPassword = isset($input['confirm_password']) ? trim($input['confirm_password']) : '';

    // Validation
    if (empty($currentPassword) || empty($newPassword) || empty($confirmPassword)) {
        echo json_encode(['success' => false, 'error' => 'All fields are required']);
        exit;
    }

    if ($newPassword !== $confirmPassword) {
        echo json_encode(['success' => false, 'error' => 'New passwords do not match']);
        exit;
    }

    if (strlen($newPassword) < 4) {
        echo json_encode(['success' => false, 'error' => 'Password must be at least 4 characters']);
        exit;
    }

    // Get current admin password using authenticated admin ID
    $sql = "SELECT id, password FROM admin WHERE id = ? LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$adminId]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$admin) {
        echo json_encode(['success' => false, 'error' => 'Admin account not found']);
        exit;
    }

    // Verify current password (plaintext comparison)
    $storedPassword = $admin['password'];
    $currentPasswordValid = ($currentPassword === $storedPassword);

    if (!$currentPasswordValid) {
        echo json_encode(['success' => false, 'error' => 'Current password is incorrect']);
        exit;
    }

    // Update password (plaintext)
    $updateSql = "UPDATE admin SET password = ? WHERE id = ?";
    $updateStmt = $pdo->prepare($updateSql);
    $updateStmt->execute([$newPassword, $admin['id']]);

    // Log password change
    logPasswordChange($admin['id']);

    // Invalidate all other tokens (force re-login on other devices)
    invalidateAllTokens($admin['id']);
    
    // Generate a new token for current session
    $newToken = generateAuthToken($admin['id']);

    echo json_encode([
        'success' => true,
        'status' => true,
        'message' => 'Password changed successfully',
        'token' => $newToken
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
