<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Not authorized']);
    exit;
}

require_once '../config/database.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $response = ['success' => false, 'message' => ''];
    
    $newUsername = $_POST['new_username'] ?? '';
    $currentPassword = $_POST['current_password'] ?? '';
    $newPassword = $_POST['new_password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    
    try {
        // Get current admin credentials
        $stmt = $conn->prepare("SELECT meta_value FROM {$tables['metadata']} WHERE meta_key = 'AdminUsername'");
        $stmt->execute();
        $currentUsername = $stmt->fetchColumn();
        
        $stmt = $conn->prepare("SELECT meta_value FROM {$tables['metadata']} WHERE meta_key = 'AdminPass'");
        $stmt->execute();
        $currentPasswordHash = $stmt->fetchColumn();
        
        // Verify current password
        if (!password_verify($currentPassword, $currentPasswordHash)) {
            $response['message'] = 'Current password is incorrect';
            echo json_encode($response);
            exit;
        }
        
        // Start transaction
        $conn->beginTransaction();
        
        // Update username if provided
        if (!empty($newUsername) && strtolower($newUsername) !== strtolower($currentUsername)) {
            // Check if username already exists (case-insensitive)
            $stmt = $conn->prepare("SELECT COUNT(*) FROM {$tables['metadata']} WHERE meta_key = 'AdminUsername' AND LOWER(meta_value) = LOWER(?)");
            $stmt->execute([$newUsername]);
            if ($stmt->fetchColumn() > 0) {
                throw new Exception('Username already exists');
            }
            
            $stmt = $conn->prepare("UPDATE {$tables['metadata']} SET meta_value = ? WHERE meta_key = 'AdminUsername'");
            $stmt->execute([$newUsername]);
            
            // Update session username
            $_SESSION['admin_username'] = $newUsername;
        }
        
        // Update password if provided
        if (!empty($newPassword)) {
            if ($newPassword !== $confirmPassword) {
                throw new Exception('New passwords do not match');
            }
            
            if (strlen($newPassword) < 6) {
                throw new Exception('Password must be at least 6 characters long');
            }
            
            $newPasswordHash = password_hash($newPassword, PASSWORD_BCRYPT);
            $stmt = $conn->prepare("UPDATE {$tables['metadata']} SET meta_value = ? WHERE meta_key = 'AdminPass'");
            $stmt->execute([$newPasswordHash]);
        }
        
        // Commit transaction
        $conn->commit();
        
        $response['success'] = true;
        $response['message'] = 'Settings updated successfully';
        
    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollBack();
        $response['message'] = $e->getMessage();
    }
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}
?> 