<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

include("check_installation.php");
include("fetch_settings.php");

if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit;
}

// Handle form submissions
if (isset($_POST["button"])) {
    // Sanitize normal input
    $bank_name          = htmlspecialchars($_POST['name']);
    $email              = htmlspecialchars($_POST['email']);
    $phone              = htmlspecialchars($_POST['phone']);
    $currency           = htmlspecialchars($_POST['currency']);
    $company_address    = htmlspecialchars($_POST['company_address']);
    $email2             = htmlspecialchars($_POST['email2']);
    $live_chat_provider = htmlspecialchars($_POST['live_chat_provider']);

    // Raw code (do not htmlspecialchars, we need <script> to remain)
    $live_chat_code = trim($_POST['live_chat_code']);

    // Validate live chat code
    if ($live_chat_provider === "tawk") {
        if (strpos($live_chat_code, "embed.tawk.to") === false) {
            $live_chat_code = "";
            $_SESSION['message'] = ['type' => 'error', 'text' => 'Invalid Tawk.to script provided!'];
        }
    } elseif ($live_chat_provider === "tidio") {
        if (strpos($live_chat_code, "code.tidio.co") === false) {
            $live_chat_code = "";
            $_SESSION['message'] = ['type' => 'error', 'text' => 'Invalid Tidio script provided!'];
        }
    } else {
        $live_chat_code = "";
    }

    $count_query = $con->prepare("SELECT COUNT(*) FROM system_settings");
    $count_query->execute();
    $count_result = $count_query->get_result();
    $count = $count_result->fetch_row()[0];
    $count_query->close();

    if ($count > 0) {
        $sql = "UPDATE system_settings 
                SET bank_name=?, email=?, phone=?, currency=?, company_address=?, email2=?, live_chat_provider=?, live_chat_code=?";
        $stmt_update = $con->prepare($sql);
        $stmt_update->bind_param('ssssssss', $bank_name, $email, $phone, $currency, $company_address, $email2, $live_chat_provider, $live_chat_code);
        if ($stmt_update->execute()) {
            if (empty($_SESSION['message'])) {
                $_SESSION['message'] = ['type' => 'success', 'text' => 'System Settings Updated Successfully!'];
            }
        } else {
            $_SESSION['message'] = ['type' => 'error', 'text' => 'Error updating settings: ' . $con->error];
        }
        $stmt_update->close();
    } else {
        $sql = "INSERT INTO system_settings (bank_name, email, phone, currency, company_address, email2, live_chat_provider, live_chat_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt_insert = $con->prepare($sql);
        $stmt_insert->bind_param('ssssssss', $bank_name, $email, $phone, $currency, $company_address, $email2, $live_chat_provider, $live_chat_code);
        if ($stmt_insert->execute()) {
            if (empty($_SESSION['message'])) {
                $_SESSION['message'] = ['type' => 'success', 'text' => 'Settings Created Successfully!'];
            }
        }
        $stmt_insert->close();
    }
    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}

// Handle brand identity form submission
if (isset($_POST["brand_button"])) {
    $upload_dir = '../assets/images/brand/';
    if (!file_exists($upload_dir)) { mkdir($upload_dir, 0777, true); }
    
    $brand_logo = ''; $favicon = ''; $success = true; $error_message = '';
    
    if (isset($_FILES['brand_logo']) && $_FILES['brand_logo']['error'] === UPLOAD_ERR_OK) {
        $file_ext = strtolower(pathinfo($_FILES['brand_logo']['name'], PATHINFO_EXTENSION));
        if (in_array($file_ext, ['jpg', 'jpeg', 'png', 'gif', 'svg'])) {
            $new_file_name = 'logo_' . time() . '.' . $file_ext;
            if (move_uploaded_file($_FILES['brand_logo']['tmp_name'], $upload_dir . $new_file_name)) {
                $brand_logo = 'assets/images/brand/' . $new_file_name;
            } else { $success = false; $error_message = 'Upload failed.'; }
        } else { $success = false; $error_message = 'Invalid logo type.'; }
    }
    
    if (isset($_FILES['favicon']) && $_FILES['favicon']['error'] === UPLOAD_ERR_OK && $success) {
        $file_ext = strtolower(pathinfo($_FILES['favicon']['name'], PATHINFO_EXTENSION));
        if (in_array($file_ext, ['ico', 'png', 'jpg', 'jpeg'])) {
            $new_file_name = 'favicon_' . time() . '.' . $file_ext;
            if (move_uploaded_file($_FILES['favicon']['tmp_name'], $upload_dir . $new_file_name)) {
                $favicon = 'assets/images/brand/' . $new_file_name;
            } else { $success = false; $error_message = 'Upload failed.'; }
        }
    }
    
    if ($success) {
        $update_fields = []; $update_values = []; $types = '';
        if (!empty($brand_logo)) { $update_fields[] = "brand_logo=?"; $update_values[] = $brand_logo; $types .= 's'; }
        if (!empty($favicon)) { $update_fields[] = "favicon=?"; $update_values[] = $favicon; $types .= 's'; }
        
        if (!empty($update_fields)) {
            $sql = "UPDATE system_settings SET " . implode(', ', $update_fields);
            $stmt_update = $con->prepare($sql);
            $stmt_update->bind_param($types, ...$update_values);
            $stmt_update->execute();
            $stmt_update->close();
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Brand Identity Updated!'];
        }
    } else { $_SESSION['message'] = ['type' => 'error', 'text' => $error_message]; }
    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}

$settings = [];
$stmt_settings = $con->prepare("SELECT * FROM system_settings LIMIT 1");
$stmt_settings->execute();
$settings = $stmt_settings->get_result()->fetch_assoc();
$stmt_settings->close();

$currencies = [];
$result_currency = $con->query("SELECT code, name FROM currency");
while ($row = $result_currency->fetch_assoc()) { $currencies[] = $row; }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Configuration | Banking Console</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="icon" href="../<?= htmlspecialchars($system_favicon); ?>">

    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap">
    <link rel="stylesheet" type="text/css" href="assets/vendor/font-awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/bootstrap-icons/bootstrap-icons.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/choices/css/choices.min.css">
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

    <style>
        :root {
            --bank-navy: #0f172a;
            --bank-blue: #2563eb;
        }

        body { font-family: 'Inter', sans-serif; background-color: #f8fafc; }

        .settings-card {
            border: none;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .nav-pills-custom .nav-link {
            color: #64748b;
            font-weight: 500;
            padding: 12px 20px;
            border-radius: 8px;
            margin-right: 10px;
            transition: all 0.2s;
        }

        .nav-pills-custom .nav-link.active {
            background-color: var(--bank-blue);
            color: white;
            box-shadow: 0 4px 6px -1px rgba(37, 99, 235, 0.2);
        }

        .form-label { font-weight: 600; font-size: 0.875rem; color: #334155; }
        .form-control, .form-select { border-radius: 8px; border: 1px solid #e2e8f0; padding: 10px 15px; }

        /* Branding Area */
        .upload-zone {
            border: 2px dashed #cbd5e1;
            border-radius: 12px;
            padding: 30px;
            text-align: center;
            background: #ffffff;
            transition: all 0.3s;
            cursor: pointer;
            position: relative;
        }

        .upload-zone:hover { border-color: var(--bank-blue); background: #f0f7ff; }
        .upload-zone i { font-size: 2.5rem; color: #94a3b8; margin-bottom: 10px; }

        .preview-box {
            background: #f1f5f9;
            border-radius: 10px;
            padding: 15px;
            display: inline-block;
            margin-top: 15px;
        }

        .preview-img { max-height: 60px; border-radius: 4px; }
        
        .section-title {
            font-size: 1rem;
            font-weight: 700;
            color: var(--bank-navy);
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
        }
        
        .section-title span {
            height: 2px;
            flex-grow: 1;
            background: #e2e8f0;
            margin-left: 15px;
        }
    </style>
</head>

<body>

<main>
    <?php include "include/sidebar.php" ?>
    
    <div class="page-content">
        <?php include "include/topbar.php" ?>
        
        <div class="page-content-wrapper p-4">
            
            <div class="d-flex align-items-center justify-content-between mb-4">
                <div>
                    <h1 class="h3 fw-bold mb-1">System Settings</h1>
                    <p class="text-muted small">Configure global parameters and brand identity.</p>
                </div>
            </div>

            <?php if (isset($_SESSION['message'])): 
                $message = $_SESSION['message']; unset($_SESSION['message']); ?>
                <script>
                    document.addEventListener('DOMContentLoaded', function() {
                        Swal.fire({
                            icon: '<?= $message['type']; ?>',
                            title: '<?= $message['type'] === 'success' ? 'Updated' : 'Error'; ?>',
                            text: '<?= $message['text']; ?>',
                            confirmButtonColor: '#2563eb'
                        });
                    });
                </script>
            <?php endif; ?>

            <div class="card settings-card">
                <div class="card-body p-4">
                    <ul class="nav nav-pills nav-pills-custom mb-5" id="pills-tab" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" data-bs-toggle="pill" data-bs-target="#general" type="button">
                                <i class="bi bi-sliders2-vertical me-2"></i>General Config
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" data-bs-toggle="pill" data-bs-target="#brand" type="button">
                                <i class="bi bi-patch-check me-2"></i>Brand Assets
                            </button>
                        </li>
                    </ul>

                    <div class="tab-content">
                        <div class="tab-pane fade show active" id="general">
                            <form method="post">
                                <h6 class="section-title">Institutional Information <span></span></h6>
                                <div class="row g-3 mb-4">
                                    <div class="col-md-8">
                                        <label class="form-label">Bank Legal Name</label>
                                        <input type="text" name="name" value="<?= htmlspecialchars($settings['bank_name'] ?? ''); ?>" class="form-control" placeholder="e.g. Global Trust Bank" required>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Operating Currency</label>
                                        <select name="currency" class="form-select js-choice">
                                            <?php foreach ($currencies as $curr): ?>
                                                <option value="<?= $curr['code']; ?>" <?= ($settings['currency'] ?? '') === $curr['code'] ? 'selected' : ''; ?>>
                                                    <?= $curr['name']; ?> (<?= $curr['code']; ?>)
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Primary Support Email</label>
                                        <input type="email" name="email" value="<?= htmlspecialchars($settings['email'] ?? ''); ?>" class="form-control" required>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Secondary / Alert Email</label>
                                        <input type="email" name="email2" value="<?= htmlspecialchars($settings['email2'] ?? ''); ?>" class="form-control">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Hotline Phone Number</label>
                                        <input type="text" name="phone" value="<?= htmlspecialchars($settings['phone'] ?? ''); ?>" class="form-control" required>
                                    </div>
                                    <div class="col-12">
                                        <label class="form-label">Headquarters Address</label>
                                        <textarea name="company_address" class="form-control" rows="2"><?= htmlspecialchars($settings['company_address'] ?? ''); ?></textarea>
                                    </div>
                                </div>

                                <h6 class="section-title">Customer Support Integration <span></span></h6>
                                <div class="row g-3">
                                    <div class="col-md-4">
                                        <label class="form-label">Live Chat Widget</label>
                                        <select name="live_chat_provider" class="form-select">
                                            <option value="">Disabled</option>
                                            <option value="tawk" <?= ($settings['live_chat_provider'] ?? '') === 'tawk' ? 'selected' : ''; ?>>Tawk.to</option>
                                            <option value="tidio" <?= ($settings['live_chat_provider'] ?? '') === 'tidio' ? 'selected' : ''; ?>>Tidio</option>
                                        </select>
                                    </div>
                                    <div class="col-md-8">
                                        <label class="form-label">Integration Script</label>
                                        <textarea name="live_chat_code" class="form-control font-monospace" rows="4" placeholder="Paste <script> here..."><?= htmlspecialchars($settings['live_chat_code'] ?? ''); ?></textarea>
                                    </div>
                                </div>

                                <div class="mt-5 border-top pt-4">
                                    <button type="submit" name="button" class="btn btn-primary px-5 rounded-pill shadow-sm">
                                        <i class="bi bi-check-circle-fill me-2"></i>Save Configuration
                                    </button>
                                </div>
                            </form>
                        </div>

                        <div class="tab-pane fade" id="brand">
                            <form method="post" enctype="multipart/form-data">
                                <div class="row g-4">
                                    <div class="col-md-6">
                                        <h6 class="section-title">Primary Logo <span></span></h6>
                                        <div class="upload-zone" onclick="document.getElementById('brand_logo').click()">
                                            <i class="bi bi-image-alt"></i>
                                            <p class="mb-0 fw-medium">Upload Brand Logo</p>
                                            <small class="text-muted">SVG or Transparent PNG (Max 5MB)</small>
                                            <input type="file" name="brand_logo" id="brand_logo" class="d-none" accept="image/*">
                                        </div>
                                        <?php if (!empty($settings['brand_logo'])): ?>
                                            <div class="preview-box">
                                                <small class="d-block text-muted mb-2">Active Logo:</small>
                                                <img src="../<?= htmlspecialchars($settings['brand_logo']); ?>" class="preview-img" alt="Logo">
                                            </div>
                                        <?php endif; ?>
                                    </div>

                                    <div class="col-md-6">
                                        <h6 class="section-title">System Favicon <span></span></h6>
                                        <div class="upload-zone" onclick="document.getElementById('favicon').click()">
                                            <i class="bi bi-app-indicator"></i>
                                            <p class="mb-0 fw-medium">Upload Favicon</p>
                                            <small class="text-muted">ICO or PNG (Recommended 32x32)</small>
                                            <input type="file" name="favicon" id="favicon" class="d-none" accept="image/*">
                                        </div>
                                        <?php if (!empty($settings['favicon'])): ?>
                                            <div class="preview-box text-center">
                                                <small class="d-block text-muted mb-2">Active Favicon:</small>
                                                <img src="../<?= htmlspecialchars($settings['favicon']); ?>" style="width: 32px;" alt="Favicon">
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <div class="mt-5 border-top pt-4">
                                    <button type="submit" name="brand_button" class="btn btn-dark px-5 rounded-pill shadow-sm">
                                        <i class="bi bi-cloud-arrow-up-fill me-2"></i>Update Brand Assets
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<script src="assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/choices/js/choices.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script src="assets/js/functions.js"></script>

<script>
    // Initialize Choices dropdown
    const choices = document.querySelectorAll('.js-choice');
    choices.forEach(el => new Choices(el, { searchEnabled: true, itemSelectText: '' }));
</script>

</body>
</html>