<?php

$pageName = "Settings";
include($_SERVER['DOCUMENT_ROOT'] . "/admin/layout/header.php");

// Make sure database connection exists
// Include your database connection file
// require_once($_SERVER['DOCUMENT_ROOT'] . "/admin/config/database.php");

// Fetch current settings
try {
    $stmt = $conn->prepare("SELECT * FROM settings WHERE id = :id");
    $stmt->execute(['id' => 1]);
    $page = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$page) {
        throw new Exception("Settings not found in database");
    }
} catch (Exception $e) {
    die("Error loading settings: " . $e->getMessage());
}

// Handle logo image upload
if (isset($_POST['upload_picture'])) {
    try {
        if (isset($_FILES['image']) && $_FILES['image']['error'] === 0) {
            $file = $_FILES['image'];
            $name = $file['name'];
            $path = pathinfo($name, PATHINFO_EXTENSION);
            $allowed = array('jpg', 'png', 'jpeg', 'svg');

            // Validate file extension
            if (!in_array(strtolower($path), $allowed)) {
                throw new Exception("Invalid file type. Only JPG, PNG, JPEG, and SVG allowed.");
            }

            // Validate file size (2MB max)
            if ($file['size'] > 2097152) {
                throw new Exception("File too large. Maximum size is 2MB.");
            }

            $folder = $_SERVER['DOCUMENT_ROOT'] . "/admin/assets/images/logo/";
            
            // Create directory if it doesn't exist
            if (!is_dir($folder)) {
                mkdir($folder, 0755, true);
            }

            // Generate unique filename to prevent overwrites
            $uniqueName = time() . '_' . basename($name);
            $destination = $folder . $uniqueName;

            if (move_uploaded_file($file['tmp_name'], $destination)) {
                $sql = "UPDATE settings SET image = :image WHERE id = :id";
                $stmt = $conn->prepare($sql);
                $stmt->execute([
                    'image' => $uniqueName,
                    'id' => 1
                ]);

                toast_alert("success", "Your Logo Uploaded Successfully", "Thanks!");
                
                // Refresh page data
                $page['image'] = $uniqueName;
            } else {
                throw new Exception("Failed to move uploaded file");
            }
        } else {
            $error_msg = isset($_FILES['image']['error']) ? $_FILES['image']['error'] : 'Unknown';
            throw new Exception("File upload error: " . $error_msg);
        }
    } catch (Exception $e) {
        toast_alert("error", $e->getMessage());
    }
}

// Handle favicon upload
if (isset($_POST['upload_favicon'])) {
    try {
        if (isset($_FILES['favicon']) && $_FILES['favicon']['error'] === 0) {
            $file = $_FILES['favicon'];
            $name = $file['name'];
            $path = pathinfo($name, PATHINFO_EXTENSION);
            $allowed = array('ico', 'png', 'svg');

            // Validate file extension
            if (!in_array(strtolower($path), $allowed)) {
                throw new Exception("Invalid file type. Only ICO, PNG, and SVG allowed.");
            }

            // Validate file size (1MB max)
            if ($file['size'] > 1048576) {
                throw new Exception("File too large. Maximum size is 1MB.");
            }

            $folder = $_SERVER['DOCUMENT_ROOT'] . "/admin/assets/images/favicon/";
            
            // Create directory if it doesn't exist
            if (!is_dir($folder)) {
                mkdir($folder, 0755, true);
            }

            // Generate unique filename to prevent overwrites
            $uniqueName = time() . '_' . basename($name);
            $destination = $folder . $uniqueName;

            if (move_uploaded_file($file['tmp_name'], $destination)) {
                $sql = "UPDATE settings SET favicon = :favicon WHERE id = :id";
                $stmt = $conn->prepare($sql);
                $stmt->execute([
                    'favicon' => $uniqueName,
                    'id' => 1
                ]);

                toast_alert("success", "Your Favicon Uploaded Successfully", "Thanks!");
                
                // Refresh page data
                $page['favicon'] = $uniqueName;
            } else {
                throw new Exception("Failed to move uploaded file");
            }
        } else {
            $error_msg = isset($_FILES['favicon']['error']) ? $_FILES['favicon']['error'] : 'Unknown';
            throw new Exception("File upload error: " . $error_msg);
        }
    } catch (Exception $e) {
        toast_alert("error", $e->getMessage());
    }
}

// Handle settings save
if (isset($_POST['save_settings'])) {
    try {
        // Validate required fields
        $required_fields = ['url_name', 'url_tel', 'url_email', 'currency'];
        foreach ($required_fields as $field) {
            if (empty($_POST[$field])) {
                throw new Exception("Field '{$field}' is required");
            }
        }

        // Sanitize and validate inputs
        $url_name = trim($_POST['url_name']);
        $url_tel = trim($_POST['url_tel']);
        $url_email = filter_var(trim($_POST['url_email']), FILTER_VALIDATE_EMAIL);
        
        if (!$url_email) {
            throw new Exception("Invalid email address");
        }

        $cardfee = floatval($_POST['cardfee']);
        $wirefee = floatval($_POST['wirefee']);
        $domesticfee = floatval($_POST['domesticfee']);
        $loanlimit = floatval($_POST['loanlimit']);
        $domesticlimit = floatval($_POST['domesticlimit']);
        $wirelimit = floatval($_POST['wirelimit']);
        // Handle dropdown values - set to 0 if empty or invalid
        $billing_code = (isset($_POST['billing_code']) && $_POST['billing_code'] !== '' && $_POST['billing_code'] !== 'Select Option') ? intval($_POST['billing_code']) : 0;
        $cot_code = (isset($_POST['cot_code']) && $_POST['cot_code'] !== '' && $_POST['cot_code'] !== 'Select Option') ? intval($_POST['cot_code']) : 0;
        $tax_code = (isset($_POST['tax_code']) && $_POST['tax_code'] !== '' && $_POST['tax_code'] !== 'Select Option') ? intval($_POST['tax_code']) : 0;
        $imf_code = (isset($_POST['imf_code']) && $_POST['imf_code'] !== '' && $_POST['imf_code'] !== 'Select Option') ? intval($_POST['imf_code']) : 0;
        $twillio_status = (isset($_POST['twillio_status']) && $_POST['twillio_status'] !== '' && $_POST['twillio_status'] !== 'Select Option') ? intval($_POST['twillio_status']) : 0;
        $currency = trim($_POST['currency']);
        $stocks = floatval($_POST['stocks']);

        $sql = "UPDATE settings SET 
                url_name = :url_name,
                url_tel = :url_tel,
                url_email = :url_email,
                cardfee = :cardfee,
                domesticfee = :domesticfee,
                wirefee = :wirefee,
                loanlimit = :loanlimit,
                domesticlimit = :domesticlimit,
                wirelimit = :wirelimit,
                billing_code = :billing_code,
                cot_code = :cot_code,
                tax_code = :tax_code,
                imf_code = :imf_code,
                twillio_status = :twillio_status,
                currency = :currency,
                stocks = :stocks 
                WHERE id = :id";
        
        $stmt = $conn->prepare($sql);
        $result = $stmt->execute([
            'url_name' => $url_name,
            'url_tel' => $url_tel,
            'url_email' => $url_email,
            'cardfee' => $cardfee,
            'domesticfee' => $domesticfee,
            'wirefee' => $wirefee,
            'loanlimit' => $loanlimit,
            'domesticlimit' => $domesticlimit,
            'wirelimit' => $wirelimit,
            'billing_code' => $billing_code,
            'cot_code' => $cot_code,
            'tax_code' => $tax_code,
            'imf_code' => $imf_code,
            'twillio_status' => $twillio_status,
            'currency' => $currency,
            'stocks' => $stocks,
            'id' => 1
        ]);

        if ($result) {
            $msg1 = "
            <div class='alert alert-warning'>
                <script type='text/javascript'>
                    function Redirect() {
                        window.location='./dashboard.php';
                    }
                    setTimeout('Redirect()', 4000);
                </script>
                <center><img src='../assets/images/loading.gif' width='180px' /></center>
                <center><strong style='color:black;'>Updated successfully, Please Wait while we redirect you...</strong></center>
            </div>";
        } else {
            throw new Exception("Database update failed");
        }
    } catch (Exception $e) {
        toast_alert('error', 'Error: ' . $e->getMessage());
    }
}

?>

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <h1>System Settings</h1>
        <ol class="breadcrumb">
            <li><a href="./dashboard.php"><i class="fa fa-dashboard"></i> Dashboard</a></li>
        </ol>
    </section>

    <!-- Main content -->
    <section class="content">
        <!-- SELECT2 EXAMPLE -->
        <div class="box box-default">
            <form method="POST">
                <div class="box-header with-border">
                    <div class="box-tools pull-right">
                        <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
                    </div>
                </div>
                <!-- /.box-header -->
                <div class="box-body">
                    <div class="row">
                        <?php if (isset($msg1)) echo $msg1; ?>

                        <div class="col-md-6">
                            <div class="form-group">
                                <label>System Name</label>
                                <input type="text" class="form-control" name="url_name" value="<?= htmlspecialchars($page['url_name']) ?>" placeholder="<?= htmlspecialchars($page['url_name']) ?>" required>
                            </div>
                            <div class="form-group">
                                <label>Request Card fee</label>
                                <input type="number" step="0.01" class="form-control" name="cardfee" value="<?= htmlspecialchars($page['cardfee']) ?>" placeholder="Card Fee">
                            </div>
                            <div class="form-group">
                                <label>Wire Transfer fee</label>
                                <input type="number" step="0.01" class="form-control" name="wirefee" value="<?= htmlspecialchars($page['wirefee']) ?>" placeholder="Wire Transfer Fee">
                            </div>
                            <div class="form-group">
                                <label>Domestic Transfer fee</label>
                                <input type="number" step="0.01" class="form-control" name="domesticfee" value="<?= htmlspecialchars($page['domesticfee']) ?>" placeholder="Domestic Transfer Fee">
                            </div>
                            <div class="form-group">
                                <label>Domestic Transfer Limit</label>
                                <input type="number" step="0.01" class="form-control" name="domesticlimit" value="<?= htmlspecialchars($page['domesticlimit']) ?>" placeholder="Domestic Transfer Limit">
                            </div>
                            <div class="form-group">
                                <label>Wire Transfer Limit</label>
                                <input type="number" step="0.01" class="form-control" name="wirelimit" value="<?= htmlspecialchars($page['wirelimit']) ?>" placeholder="Wire Transfer Limit">
                            </div>
                            <div class="form-group">
                                <label>Billing Code Option</label>
                                <select class="form-control select2" name="billing_code" style="width: 100%;" required>
                                    <option value="1" <?= (isset($page['billing_code']) && $page['billing_code'] == 1) ? 'selected' : '' ?>>On</option>
                                    <option value="0" <?= (!isset($page['billing_code']) || $page['billing_code'] == 0) ? 'selected' : '' ?>>Off</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>COT Code Option</label>
                                <select class="form-control select2" name="cot_code" style="width: 100%;" required>
                                    <option value="1" <?= (isset($page['cot_code']) && $page['cot_code'] == 1) ? 'selected' : '' ?>>On</option>
                                    <option value="0" <?= (!isset($page['cot_code']) || $page['cot_code'] == 0) ? 'selected' : '' ?>>Off</option>
                                </select>
                            </div>
                        </div>
                        
                        <!-- /.col -->
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>System Email</label>
                                <input type="email" class="form-control" name="url_email" value="<?= htmlspecialchars($page['url_email']) ?>" placeholder="<?= htmlspecialchars($page['url_email']) ?>" required>
                            </div>
                            <div class="form-group">
                                <label>System Phone</label>
                                <input type="text" class="form-control" name="url_tel" value="<?= htmlspecialchars($page['url_tel']) ?>" placeholder="<?= htmlspecialchars($page['url_tel']) ?>" required>
                            </div>
                            <div class="form-group">
                                <label>System Currency</label>
                                <input type="text" class="form-control" name="currency" value="<?= htmlspecialchars($page['currency']) ?>" placeholder="System Currency" required>
                            </div>
                            <div class="form-group">
                                <label>Loan Limit</label>
                                <input type="number" step="0.01" class="form-control" name="loanlimit" value="<?= htmlspecialchars($page['loanlimit']) ?>" placeholder="Loan Limit">
                            </div>
                            <div class="form-group">
                                <label>Stock Interest (USD)</label>
                                <input type="number" step="0.01" class="form-control" name="stocks" value="<?= htmlspecialchars($page['stocks']) ?>" placeholder="0.00">
                            </div>
                            <div class="form-group">
                                <label>Twillio Config Option</label>
                                <select class="form-control select2" name="twillio_status" style="width: 100%;" required>
                                    <option value="1" <?= (isset($page['twillio_status']) && $page['twillio_status'] == 1) ? 'selected' : '' ?>>On</option>
                                    <option value="0" <?= (!isset($page['twillio_status']) || $page['twillio_status'] == 0) ? 'selected' : '' ?>>Off</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>TAX Code Option</label>
                                <select class="form-control select2" name="tax_code" style="width: 100%;" required>
                                    <option value="1" <?= (isset($page['tax_code']) && $page['tax_code'] == 1) ? 'selected' : '' ?>>On</option>
                                    <option value="0" <?= (!isset($page['tax_code']) || $page['tax_code'] == 0) ? 'selected' : '' ?>>Off</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>IMF Code Option</label>
                                <select class="form-control select2" name="imf_code" style="width: 100%;" required>
                                    <option value="1" <?= (isset($page['imf_code']) && $page['imf_code'] == 1) ? 'selected' : '' ?>>On</option>
                                    <option value="0" <?= (!isset($page['imf_code']) || $page['imf_code'] == 0) ? 'selected' : '' ?>>Off</option>
                                </select>
                            </div>
                        </div>
                        <!-- /.col -->
                    </div>
                    <!-- /.row -->
                </div>
                <!-- /.box-body -->
                <div class="box-footer">
                    <button type="submit" name="save_settings" class="btn btn-primary">Save Settings</button>
                </div>
            </form>
        </div>

        <!-- Logo Upload Box -->
        <div class="box box-default">
            <div class="box-header with-border">
                <h3 class="box-title">Logo Image</h3>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <div class="box-body">
                    <div class="form-group">
                        <input type="file" id="input-file-max-fs" class="form-control" name="image" accept="image/jpeg,image/png,image/jpg,image/svg+xml" required />
                        <small class="help-block">Maximum file size: 2MB. Allowed formats: JPG, PNG, JPEG, SVG</small>
                    </div>
                    <?php if (isset($page['image']) && !empty($page['image'])): ?>
                        <div class="form-group">
                            <label>Current Logo:</label><br>
                            <img src="/admin/assets/images/logo/<?= htmlspecialchars($page['image']) ?>" alt="Current Logo" style="max-width: 200px; max-height: 100px;">
                        </div>
                    <?php endif; ?>
                </div>
                <div class="box-footer">
                    <button type="submit" name="upload_picture" class="btn btn-primary">Upload Image</button>
                </div>
            </form>
        </div>
        <!-- /.box -->

        <!-- Favicon Upload Box -->
        <div class="box box-default">
            <div class="box-header with-border">
                <h3 class="box-title">Favicon</h3>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <div class="box-body">
                    <div class="form-group">
                        <input type="file" class="form-control" name="favicon" accept="image/x-icon,image/png,image/svg+xml" required />
                        <small class="help-block">Maximum file size: 1MB. Allowed formats: ICO, PNG, SVG. Recommended size: 32x32 or 16x16 pixels.</small>
                    </div>
                    <?php if (isset($page['favicon']) && !empty($page['favicon'])): ?>
                        <div class="form-group">
                            <label>Current Favicon:</label><br>
                            <img src="/admin/assets/images/favicon/<?= htmlspecialchars($page['favicon']) ?>" alt="Current Favicon" style="max-width: 64px; max-height: 64px;">
                        </div>
                    <?php endif; ?>
                </div>
                <div class="box-footer">
                    <button type="submit" name="upload_favicon" class="btn btn-primary">Upload Favicon</button>
                </div>
            </form>
        </div>
        <!-- /.box -->

    </section>
    <!-- /.content -->
</div>
<!-- /.content-wrapper -->

<?php
include($_SERVER['DOCUMENT_ROOT'] . "/admin/layout/footer.php");
?>