<?php
session_start();
require_once '../config/config.php';

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

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

// Validate and sanitize input
$first_reminder = isset($_POST['first_reminder']) ? (int)$_POST['first_reminder'] : 60;
$second_reminder = isset($_POST['second_reminder']) ? (int)$_POST['second_reminder'] : 30;
$final_reminder = isset($_POST['final_reminder']) ? (int)$_POST['final_reminder'] : 7;
$grace_period = isset($_POST['grace_period']) ? (int)$_POST['grace_period'] : 30;
$renewal_fee = isset($_POST['renewal_fee']) ? (float)$_POST['renewal_fee'] : 1000;
$late_fee = isset($_POST['late_fee']) ? (float)$_POST['late_fee'] : 200;
$auto_renewal = isset($_POST['auto_renewal']) ? ($_POST['auto_renewal'] === 'true' || $_POST['auto_renewal'] === '1' || $_POST['auto_renewal'] === true) : false;

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Check if settings already exist
    $stmt = $conn->query("SELECT COUNT(*) FROM system_settings WHERE category = 'renewal'");
    $settings_exist = $stmt->fetchColumn() > 0;
    
    if ($settings_exist) {
        // Update existing settings
        $stmt = $conn->prepare("
            UPDATE system_settings 
            SET 
                value = CASE setting_key
                    WHEN 'first_reminder' THEN ?
                    WHEN 'second_reminder' THEN ?
                    WHEN 'final_reminder' THEN ?
                    WHEN 'grace_period' THEN ?
                    WHEN 'renewal_fee' THEN ?
                    WHEN 'late_fee' THEN ?
                    WHEN 'auto_renewal' THEN ?
                END,
                updated_at = CURRENT_TIMESTAMP
            WHERE category = 'renewal' AND setting_key IN ('first_reminder', 'second_reminder', 'final_reminder', 'grace_period', 'renewal_fee', 'late_fee', 'auto_renewal')
        ");
        $stmt->execute([
            $first_reminder,
            $second_reminder,
            $final_reminder,
            $grace_period,
            $renewal_fee,
            $late_fee,
            $auto_renewal ? '1' : '0'
        ]);
    } else {
        // Insert new settings
        $settings = [
            ['renewal', 'first_reminder', $first_reminder],
            ['renewal', 'second_reminder', $second_reminder],
            ['renewal', 'final_reminder', $final_reminder],
            ['renewal', 'grace_period', $grace_period],
            ['renewal', 'renewal_fee', $renewal_fee],
            ['renewal', 'late_fee', $late_fee],
            ['renewal', 'auto_renewal', $auto_renewal ? '1' : '0']
        ];
        
        $stmt = $conn->prepare("
            INSERT INTO system_settings (category, setting_key, value, created_at, updated_at)
            VALUES (?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
        ");
        
        foreach ($settings as $setting) {
            $stmt->execute($setting);
        }
    }
    
    // Log the action
    $stmt = $conn->prepare("
        INSERT INTO admin_logs (admin_id, action, details, created_at)
        VALUES (?, 'update_settings', 'Updated renewal settings', CURRENT_TIMESTAMP)
    ");
    $stmt->execute([$_SESSION['admin_id']]);
    
    echo json_encode([
        'success' => true,
        'message' => 'Settings saved successfully'
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
