<?php
require_once 'header.php';

// Suraksha jaanch: Sirf zaroori roles waale users hi is page ko access kar sakte hain.
if (!userHasRole(['Admin', 'Sales'])) {
    echo "<div class='p-6'>Access Denied. You do not have permission to view this page.</div>";
    require_once 'footer.php';
    exit();
}

$message = '';
$message_type = '';

// Function to save or update a setting
function save_setting($conn, $key, $value) {
    $stmt = $conn->prepare("INSERT INTO app_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
    $stmt->bind_param("ss", $key, $value);
    return $stmt->execute();
}

// Form submission logic
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $settings_to_save = [
        'company_name' => $_POST['company_name'],
        'company_address' => $_POST['company_address'],
        'company_pan_gst' => $_POST['company_pan_gst'],
        'bank_details' => $_POST['bank_details'],
        'invoice_notes' => $_POST['invoice_notes']
    ];

    $all_saved = true;
    foreach ($settings_to_save as $key => $value) {
        if (!save_setting($conn, $key, $value)) {
            $all_saved = false;
        }
    }

    // Handle Company Logo Upload
    if (isset($_FILES['company_logo']) && $_FILES['company_logo']['error'] == 0) {
        $target_dir = "uploads/logos/";
        if (!is_dir($target_dir)) mkdir($target_dir, 0755, true);
        $target_file = $target_dir . uniqid() . '_' . basename($_FILES["company_logo"]["name"]);
        if (move_uploaded_file($_FILES["company_logo"]["tmp_name"], $target_file)) {
            save_setting($conn, 'company_logo', $target_file);
        } else {
            $all_saved = false;
        }
    }
    
    // Handle QR Code Upload
    if (isset($_FILES['payment_qr_code']) && $_FILES['payment_qr_code']['error'] == 0) {
        $target_dir = "uploads/qr/";
        if (!is_dir($target_dir)) mkdir($target_dir, 0755, true);
        $target_file = $target_dir . uniqid() . '_' . basename($_FILES["payment_qr_code"]["name"]);
        if (move_uploaded_file($_FILES["payment_qr_code"]["tmp_name"], $target_file)) {
            save_setting($conn, 'payment_qr_code', $target_file);
        } else {
            $all_saved = false;
        }
    }

    if ($all_saved) {
        $message = "Settings saved successfully!";
        $message_type = 'success';
    } else {
        $message = "An error occurred while saving settings.";
        $message_type = 'error';
    }
}

// Fetch current settings
$settings = [];
$settings_result = $conn->query("SELECT * FROM app_settings");
while ($row = $settings_result->fetch_assoc()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}
?>
<title>Invoice Settings - Digify OS</title>

<div class="p-6 md:p-10">
    <header class="mb-6">
        <h2 class="text-2xl font-bold text-gray-800">Invoice Settings</h2>
        <p class="text-gray-600">These details will appear on all your invoices.</p>
    </header>

    <?php if ($message): ?>
    <div class="mb-4 p-4 rounded-lg <?php echo ($message_type == 'error') ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'; ?>">
        <?php echo htmlspecialchars($message); ?>
    </div>
    <?php endif; ?>

    <form method="POST" action="invoice-settings.php" enctype="multipart/form-data" class="bg-white p-8 rounded-lg shadow-md">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
            <!-- Company Details -->
            <div class="space-y-6">
                <div>
                    <label for="company_name" class="block text-sm font-medium text-gray-700">Company Name</label>
                    <input type="text" id="company_name" name="company_name" value="<?php echo htmlspecialchars($settings['company_name'] ?? ''); ?>" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                </div>
                <div>
                    <label for="company_address" class="block text-sm font-medium text-gray-700">Company Address</label>
                    <textarea id="company_address" name="company_address" rows="3" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"><?php echo htmlspecialchars($settings['company_address'] ?? ''); ?></textarea>
                </div>
                <div>
                    <label for="company_pan_gst" class="block text-sm font-medium text-gray-700">PAN / GST Number</label>
                    <input type="text" id="company_pan_gst" name="company_pan_gst" value="<?php echo htmlspecialchars($settings['company_pan_gst'] ?? ''); ?>" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Company Logo</label>
                    <input type="file" name="company_logo" class="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
                    <?php if (!empty($settings['company_logo'])): ?>
                        <img src="<?php echo htmlspecialchars($settings['company_logo']); ?>" alt="Current Logo" class="mt-2 h-16 w-auto">
                    <?php endif; ?>
                </div>
            </div>
            <!-- Invoice Footer Details -->
            <div class="space-y-6">
                <div>
                    <label for="bank_details" class="block text-sm font-medium text-gray-700">Bank Details</label>
                    <textarea id="bank_details" name="bank_details" rows="4" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm" placeholder="e.g.&#10;Bank Name: HDFC BANK&#10;Account No: 1234567890&#10;IFSC: HDFC0001234"><?php echo htmlspecialchars($settings['bank_details'] ?? ''); ?></textarea>
                </div>
                <div>
                    <label for="invoice_notes" class="block text-sm font-medium text-gray-700">Notes / Terms & Conditions</label>
                    <textarea id="invoice_notes" name="invoice_notes" rows="4" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"><?php echo htmlspecialchars($settings['invoice_notes'] ?? ''); ?></textarea>
                </div>
                 <div>
                    <label class="block text-sm font-medium text-gray-700">Payment QR Code</label>
                    <input type="file" name="payment_qr_code" class="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
                     <?php if (!empty($settings['payment_qr_code'])): ?>
                        <img src="<?php echo htmlspecialchars($settings['payment_qr_code']); ?>" alt="Current QR Code" class="mt-2 h-24 w-24">
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="mt-8 text-right">
            <button type="submit" class="px-8 py-3 bg-blue-600 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700">Save Settings</button>
        </div>
    </form>
</div>

