<?php
session_start();
include 'layouts/dbconn.php';

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

//if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
//    echo json_encode(['success' => false, 'error' => 'Not authorized']);
//    exit;
//}

try {
    // Validate inputs
    $phcf = floatval($_POST['phcf_percentage'] ?? 0);
    $tl = floatval($_POST['training_levy'] ?? 0);
    $stamp_duty = floatval($_POST['stamp_duty'] ?? 0);
    
    if ($phcf < 0 || $phcf > 100) {
        throw new Exception('Invalid PHCF percentage');
    }
    
    if ($tl < 0 || $tl > 100) {
        throw new Exception('Invalid Training Levy');
    }
    
    if ($stamp_duty < 0) {
        throw new Exception('Invalid stamp duty amount');
    }
    
    // Start transaction
    $conn->begin_transaction();
    
    // Update PHCF setting
    $sql = "UPDATE settings SET setting_value = ? WHERE setting_key = 'phcf_percentage'";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $_POST['phcf_percentage']);
    if (!$stmt->execute()) {
        throw new Exception('Failed to update PHCF setting');
    }
    
    // Update TL setting
    $sql = "UPDATE settings SET setting_value = ? WHERE setting_key = 'training_levy'";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $_POST['training_levy']);
    if (!$stmt->execute()) {
        throw new Exception('Failed to update TL setting');
    }
    
    // Update stamp duty setting
    $sql = "UPDATE settings SET setting_value = ? WHERE setting_key = 'stamp_duty'";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $_POST['stamp_duty']);
    if (!$stmt->execute()) {
        throw new Exception('Failed to update stamp duty setting');
    }
    
    // Log the change
    $sql = "INSERT INTO activity_log (
        user_id, 
        action, 
        table_name, 
        record_id,
        new_values,
        ip_address,
        user_agent,
        action_date
    ) VALUES (?, 'UPDATE', 'settings', 'tax', ?, ?, ?, NOW())";
    
    $stmt = $conn->prepare($sql);
    $new_values = json_encode([
        'phcf_percentage' => $phcf,
        'training_levy' => $tl,
        'stamp_duty' => $stamp_duty
    ]);
    
    $stmt->bind_param('ssss',
        $_SESSION['user_id'],
        $new_values,
        $_SERVER['REMOTE_ADDR'],
        $_SERVER['HTTP_USER_AGENT']
    );
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to log changes');
    }
    
    // Commit transaction
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Tax settings updated successfully'
    ]);
    
} catch (Exception $e) {
    if ($conn->inTransaction()) {
        $conn->rollback();
    }
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>