<?php
session_start();

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header("Location: login.php");
    exit();
}

// Handle tool creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_tool'])) {
    $tool_name = preg_replace('/[^a-zA-Z]/', '', $_POST['new_tool']);
    if (!empty($tool_name)) {
        $filename = strtolower($tool_name) . '.php';
        
        if (!file_exists($filename)) {
            // Create new tool file with enhanced dashboard link
            $template = <<<EOT
<?php
session_start();
if (!isset(\$_SESSION['loggedin']) || \$_SESSION['loggedin'] !== true) {
    header("Location: login.php");
    exit();
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>$tool_name Tool</title>
    <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">
    <link rel="stylesheet" href="dist/css/adminlte.min.css">
    <style>
        .dashboard-container {
            text-align: center;
            margin: 20px 0;
        }
        .dashboard-link {
            display: inline-block;
            padding: 10px 20px;
            background: #4285F4;
            color: white;
            border-radius: 4px;
            text-decoration: none;
            font-weight: 500;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
            transition: all 0.3s;
        }
        .dashboard-link:hover {
            background: #3367D6;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            transform: translateY(-2px);
        }
        .dashboard-link i {
            margin-right: 8px;
        }
    </style>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <!-- Google-style Dashboard Link -->
    <div class="dashboard-container">
        <a href="dashboard.php" class="dashboard-link">
            <i class="fas fa-home"></i> Back to Dashboard
        </a>
    </div>

    <div class="content-wrapper">
        <section class="content">
            <div class="container-fluid">
                <!-- SECTION_START -->
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">$tool_name Cookies</h3>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label for="{$tool_name}Url">URL</label>
                            <input type="text" class="form-control" id="{$tool_name}Url" data-service="{$tool_name}" placeholder="URL">
                        </div>
                        <div class="form-group">
                            <label for="{$tool_name}Cookies">Cookies</label>
                            <input type="text" class="form-control" id="{$tool_name}Cookies" data-service="{$tool_name}" placeholder="json">
                        </div>
                    </div>
                    <div class="card-footer">
                        <button type="button" onclick="saveCookiesData('$tool_name')" class="btn btn-primary">Save {$tool_name} Cookies</button>
                        <div id="{$tool_name}SuccessMessage" style="display:none;color:green;">{$tool_name} Cookies saved successfully!</div>
                    </div>
                </div>
                <!-- SECTION_END -->
                
                <script src="plugins/jquery/jquery.min.js"></script>
                <script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
                <script src="dist/js/adminlte.min.js"></script>
                <script src="dist/js/pages/custom.js"></script>
            </div>
        </section>
    </div>
</div>
</body>
</html>
EOT;
            file_put_contents($filename, $template);
            $success = "Tool '{$tool_name}' created successfully!";
        } else {
            $error = "A tool with that name already exists!";
        }
    } else {
        $error = "Invalid tool name! Only letters are allowed.";
    }
}

// Handle adding/replacing text fields
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_fields'])) {
    $tool_file = $_POST['tool_file'];
    $num_fields = (int)$_POST['num_fields'];
    
    if (file_exists($tool_file) && $num_fields > 0) {
        $content = file_get_contents($tool_file);
        
        $section_start = strpos($content, '<!-- SECTION_START -->');
        $section_end = strpos($content, '<!-- SECTION_END -->');
        
        if ($section_start !== false && $section_end !== false) {
            $section = substr($content, $section_start, $section_end - $section_start);
            
            preg_match('/<h3 class="card-title">([a-zA-Z]+)/', $section, $name_match);
            $tool_name = $name_match[1] ?? 'Tool';
            $lower_name = strtolower($tool_name);
            
            $new_fields = '';
            for ($i = 1; $i <= $num_fields; $i++) {
                $new_fields .= str_replace(
                    [
                        "<h3 class=\"card-title\">{$tool_name} Cookies</h3>",
                        "id=\"{$lower_name}Url\"",
                        "id=\"{$lower_name}Cookies\"",
                        "id=\"{$lower_name}SuccessMessage\"",
                        "data-service=\"{$lower_name}\"",
                        "onclick=\"saveCookiesData('{$lower_name}')\"",
                        ">{$tool_name} Cookies saved successfully!"
                    ],
                    [
                        "<h3 class=\"card-title\">{$tool_name} {$i} Cookies</h3>",
                        "id=\"{$lower_name}{$i}Url\"",
                        "id=\"{$lower_name}{$i}Cookies\"",
                        "id=\"{$lower_name}{$i}SuccessMessage\"",
                        "data-service=\"{$lower_name}{$i}\"",
                        "onclick=\"saveCookiesData('{$lower_name}{$i}')\"",
                        ">{$tool_name} {$i} Cookies saved successfully!"
                    ],
                    $section
                );
            }
            
            $new_content = substr($content, 0, $section_start) . 
                          '<!-- SECTION_START -->' . $new_fields . '<!-- SECTION_END -->' .
                          substr($content, $section_end + strlen('<!-- SECTION_END -->'));
            
            file_put_contents($tool_file, $new_content);
            $success = "Created {$num_fields} new text field sections in {$tool_file}!";
        } else {
            $error = "Could not find section markers in the file.";
        }
    } else {
        $error = "Invalid file or number of fields specified.";
    }
}

// Get list of existing tool files (excluding system files)
$tool_files = glob('*.php');
$excluded_files = ['login.php', 'dashboard.php', 'logout.php', 'footer.php', 'default.php'];
$tool_files = array_filter($tool_files, function($file) use ($excluded_files) {
    return !in_array($file, $excluded_files);
});

// Handle search
$search_term = $_GET['search'] ?? '';
$filtered_files = [];
if (!empty($search_term)) {
    foreach ($tool_files as $file) {
        if (stripos($file, $search_term) !== false) {
            $filtered_files[] = $file;
        }
    }
} else {
    $filtered_files = $tool_files;
}

// Get icons for different tool types
function getToolIcon($tool_name) {
    $icons = [
        'seo' => 'fa-search-dollar',
        'analytics' => 'fa-chart-line',
        'social' => 'fa-share-alt',
        'content' => 'fa-file-alt',
        'chat' => 'fa-comments',
        'default' => 'fa-cube'
    ];
    
    $tool_lower = strtolower($tool_name);
    
    foreach ($icons as $key => $icon) {
        if (strpos($tool_lower, $key) !== false) {
            return $icon;
        }
    }
    
    return $icons['default'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>AI IT Sotlution | Dashboard</title>
    <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">
    <link rel="stylesheet" href="dist/css/adminlte.min.css">
    <style>
        .sidebar-dark-primary .nav-sidebar > .nav-item > .nav-link.active {
            background-color: #4e73df;
        }
        .nav-icon {
            width: 1.2rem;
            text-align: center;
            margin-right: 0.5rem;
        }
        .tool-card {
            transition: all 0.3s;
            border-top: 3px solid #4e73df;
        }
        .tool-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .search-box {
            border-radius: 20px;
            padding-left: 40px;
        }
        .search-icon {
            position: absolute;
            z-index: 2;
            display: block;
            width: 2.375rem;
            height: 2.375rem;
            line-height: 2.375rem;
            text-align: center;
            pointer-events: none;
            color: #aaa;
        }
        .brand-link {
            border-bottom: 1px solid #4a5568;
        }
        .nav-pills .nav-link.active {
            background-color: rgba(78, 115, 223, 0.1);
            color: #4e73df;
        }
        .table-hover tbody tr:hover {
            background-color: rgba(78, 115, 223, 0.05);
        }
    </style>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <!-- Navbar -->
    <nav class="main-header navbar navbar-expand navbar-white navbar-light border-bottom-0">
        <!-- Left navbar links -->
        <ul class="navbar-nav">
            <li class="nav-item">
                <a class="nav-link" data-widget="pushmenu" href="#"><i class="fas fa-bars"></i></a>
            </li>
        </ul>

        <!-- Search Form -->
        <div class="ml-auto" style="width: 300px;">
            <form action="dashboard.php" method="get">
                <div class="input-group">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-white border-0">
                            <i class="fas fa-search"></i>
                        </span>
                    </div>
                    <input type="search" name="search" class="form-control form-control-navbar search-box" 
                           placeholder="Search tools..." value="<?= htmlspecialchars($search_term) ?>">
                </div>
            </form>
        </div>

        <!-- Right navbar links -->
        <ul class="navbar-nav ml-auto">
            <li class="nav-item dropdown">
                <a class="nav-link" data-toggle="dropdown" href="#">
                    <i class="far fa-user-circle fa-lg"></i>
                </a>
                <div class="dropdown-menu dropdown-menu-right">
                    <a href="logout.php" class="dropdown-item">
                        <i class="fas fa-sign-out-alt mr-2"></i> Logout
                    </a>
                </div>
            </li>
        </ul>
    </nav>

    <!-- Sidebar -->
    <aside class="main-sidebar sidebar-dark-primary elevation-4">
        <!-- Brand Logo -->
        <a href="dashboard.php" class="brand-link text-center">
            <span class="brand-text font-weight-light"><b>AI IT Solution Tools</b> </span>
        </a>

        <!-- Sidebar -->
        <div class="sidebar">
            <!-- Sidebar Menu -->
            <nav class="mt-3">
                <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu">
                    <li class="nav-item">
                        <a href="dashboard.php" class="nav-link active">
                            <i class="nav-icon fas fa-tachometer-alt"></i>
                            <p>Dashboard</p>
                        </a>
                    </li>
                    <li class="nav-header">YOUR TOOLS</li>
                    <?php foreach ($tool_files as $file): 
                        $tool_name = pathinfo($file, PATHINFO_FILENAME);
                        $display_name = $search_term ? 
                            preg_replace("/(".$search_term.")/i", '<span class="text-warning">$1</span>', $tool_name) : 
                            $tool_name;
                    ?>
                    <li class="nav-item">
                        <a href="<?= htmlspecialchars($file) ?>" class="nav-link">
                            <i class="nav-icon fas <?= getToolIcon($tool_name) ?>"></i>
                            <p><?= $display_name ?></p>
                        </a>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </nav>
        </div>
    </aside>

    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <!-- Content Header -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0 text-dark">Dashboard</h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item active">Dashboard</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
                <?php if (isset($error)): ?>
                <div class="alert alert-danger alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    <i class="icon fas fa-ban"></i> <?= htmlspecialchars($error) ?>
                </div>
                <?php endif; ?>
                <?php if (isset($success)): ?>
                <div class="alert alert-success alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    <i class="icon fas fa-check"></i> <?= htmlspecialchars($success) ?>
                </div>
                <?php endif; ?>

                <div class="row">
                    <div class="col-lg-6">
                        <div class="card tool-card">
                            <div class="card-header">
                                <h3 class="card-title"><i class="fas fa-plus-circle mr-2"></i>Create New Tool</h3>
                            </div>
                            <div class="card-body">
                                <form method="POST">
                                    <div class="form-group">
                                        <label>Tool Name</label>
                                        <div class="input-group">
                                            <div class="input-group-prepend">
                                                <span class="input-group-text"><i class="fas fa-cog"></i></span>
                                            </div>
                                            <input type="text" class="form-control" name="new_tool" 
                                                   required pattern="[A-Za-z]+" placeholder="Enter tool name">
                                        </div>
                                        <small class="text-muted">Only letters allowed (no spaces or special characters)</small>
                                    </div>
                                    <button type="submit" class="btn btn-primary btn-block">
                                        <i class="fas fa-plus mr-2"></i> Create Tool
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-6">
                        <div class="card tool-card">
                            <div class="card-header">
                                <h3 class="card-title"><i class="fas fa-edit mr-2"></i>Manage Tool Fields</h3>
                            </div>
                            <div class="card-body">
                                <form method="POST">
                                    <div class="form-group">
                                        <label>Select Tool</label>
                                        <select class="form-control select2" name="tool_file" required style="width: 100%;">
                                            <?php foreach ($tool_files as $file): ?>
                                            <option value="<?= htmlspecialchars($file) ?>">
                                                <?= htmlspecialchars(pathinfo($file, PATHINFO_FILENAME)) ?>
                                            </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label>Number of Fields</label>
                                        <input type="number" class="form-control" name="num_fields" 
                                               min="1" value="5" required>
                                    </div>
                                    <button type="submit" name="add_fields" class="btn btn-primary btn-block">
                                        <i class="fas fa-sync-alt mr-2"></i> Update Fields
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row mt-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title"><i class="fas fa-th-list mr-2"></i>Your Tools</h3>
                                <div class="card-tools">
                                    <span class="badge badge-primary"><?= count($filtered_files) ?> tools</span>
                                </div>
                            </div>
                            <div class="card-body p-0">
                                <?php if (empty($filtered_files)): ?>
                                <div class="text-center p-5">
                                    <i class="fas fa-folder-open fa-3x text-gray-300 mb-3"></i>
                                    <h4 class="text-gray-500">No tools found</h4>
                                    <p class="text-muted">Create your first tool using the form above</p>
                                </div>
                                <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-hover text-nowrap">
                                        <thead>
                                            <tr>
                                                <th style="width: 40px"></th>
                                                <th>Tool Name</th>
                                                <th style="width: 100px">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($filtered_files as $file): 
                                                $tool_name = pathinfo($file, PATHINFO_FILENAME);
                                                $display_name = $search_term ? 
                                                    preg_replace("/(".$search_term.")/i", '<span class="text-warning">$1</span>', $tool_name) : 
                                                    $tool_name;
                                            ?>
                                            <tr>
                                                <td><i class="fas <?= getToolIcon($tool_name) ?> text-primary"></i></td>
                                                <td><?= $display_name ?></td>
                                                <td>
                                                    <a href="<?= htmlspecialchars($file) ?>" class="btn btn-sm btn-primary">
                                                        <i class="fas fa-external-link-alt"></i> Open
                                                    </a>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>

    <!-- Footer -->
    <footer class="main-footer">
        <div class="float-right d-none d-sm-block">
            <b>Version</b> 1.0.0
        </div>
        <strong>Copyright &copy; <?php echo date('Y'); ?> <a href="https://wa.me/01905353543">Ai It Solution</a>.</strong> All rights reserved.
    </footer>
</div>

<!-- REQUIRED SCRIPTS -->
<script src="plugins/jquery/jquery.min.js"></script>
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="dist/js/adminlte.min.js"></script>
<script>
$(document).ready(function() {
    // Initialize select2
    $('.select2').select2({
        theme: 'bootstrap4'
    });

    // Auto-refresh when new tools are created
    $('form').on('submit', function() {
        if ($(this).find('[name="new_tool"]').length) {
            setTimeout(function() {
                location.reload();
            }, 1000);
        }
    });
    
    // Highlight search terms
    const urlParams = new URLSearchParams(window.location.search);
    const searchTerm = urlParams.get('search');
    if (searchTerm) {
        $('input[name="search"]').focus();
    }
});
</script>
</body>
</html>