<?php
declare(strict_types=1);

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'auth.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'storage.php';

require_login();

$page = (string)($_GET['page'] ?? 'dashboard');
$allowedPages = ['dashboard', 'profile', 'announcements', 'customers', 'files'];
if (!in_array($page, $allowedPages, true)) {
    $page = 'dashboard';
}

$flash = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');

    if ($action === 'update_profile') {
        $profile = [
            'company_name' => trim((string)($_POST['company_name'] ?? APP_NAME)),
            'slogan' => trim((string)($_POST['slogan'] ?? '')),
            'phone' => trim((string)($_POST['phone'] ?? '')),
            'email' => trim((string)($_POST['email'] ?? '')),
            'address' => trim((string)($_POST['address'] ?? '')),
            'about' => trim((string)($_POST['about'] ?? '')),
        ];
        write_json_data('profile', $profile);
        $_SESSION['flash'] = '企业信息已更新';
        header('Location: index.php?page=profile');
        exit;
    }

    if ($action === 'add_announcement') {
        $title = trim((string)($_POST['title'] ?? ''));
        $content = trim((string)($_POST['content'] ?? ''));
        if ($title !== '' && $content !== '') {
            $list = read_json_data('announcements', []);
            array_unshift($list, [
                'id' => generate_id(),
                'title' => $title,
                'content' => $content,
                'created_at' => date('Y-m-d H:i:s'),
            ]);
            write_json_data('announcements', $list);
            $_SESSION['flash'] = '公告已发布';
        }
        header('Location: index.php?page=announcements');
        exit;
    }

    if ($action === 'delete_announcement') {
        $id = (string)($_POST['id'] ?? '');
        $list = read_json_data('announcements', []);
        $list = array_values(array_filter($list, static function (array $item) use ($id): bool {
            return (string)$item['id'] !== $id;
        }));
        write_json_data('announcements', $list);
        $_SESSION['flash'] = '公告已删除';
        header('Location: index.php?page=announcements');
        exit;
    }

    if ($action === 'add_customer') {
        $name = trim((string)($_POST['name'] ?? ''));
        $contact = trim((string)($_POST['contact'] ?? ''));
        $plan = trim((string)($_POST['plan'] ?? '标准版'));
        $status = trim((string)($_POST['status'] ?? '跟进中'));
        if ($name !== '' && $contact !== '') {
            $customers = read_json_data('customers', []);
            array_unshift($customers, [
                'id' => generate_id(),
                'name' => $name,
                'contact' => $contact,
                'plan' => $plan,
                'status' => $status,
                'created_at' => date('Y-m-d H:i:s'),
            ]);
            write_json_data('customers', $customers);
            $_SESSION['flash'] = '客户已新增';
        }
        header('Location: index.php?page=customers');
        exit;
    }

    if ($action === 'delete_customer') {
        $id = (string)($_POST['id'] ?? '');
        $customers = read_json_data('customers', []);
        $customers = array_values(array_filter($customers, static function (array $item) use ($id): bool {
            return (string)$item['id'] !== $id;
        }));
        write_json_data('customers', $customers);
        $_SESSION['flash'] = '客户已删除';
        header('Location: index.php?page=customers');
        exit;
    }

    if ($action === 'upload_file') {
        $files = read_json_data('files', []);
        if (isset($_FILES['upload_file']) && is_array($_FILES['upload_file'])) {
            $uploaded = $_FILES['upload_file'];
            if (($uploaded['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_OK) {
                $maxSize = 10 * 1024 * 1024;
                $size = (int)($uploaded['size'] ?? 0);
                $originalName = (string)($uploaded['name'] ?? '');
                $ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
                $allowed = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'jpg', 'jpeg', 'png', 'zip', 'txt', 'php'];
                if ($size > 0 && $size <= $maxSize && in_array($ext, $allowed, true)) {
                    $safeName = preg_replace('/[^a-zA-Z0-9\._-]/', '_', $originalName);
                    $storedName = date('YmdHis') . '_' . generate_id() . '_' . $safeName;
                    $target = UPLOAD_DIR . DIRECTORY_SEPARATOR . $storedName;
                    if (move_uploaded_file((string)$uploaded['tmp_name'], $target)) {
                        array_unshift($files, [
                            'id' => generate_id(),
                            'original_name' => $originalName,
                            'stored_name' => $storedName,
                            'size' => $size,
                            'uploaded_at' => date('Y-m-d H:i:s'),
                        ]);
                        write_json_data('files', $files);
                        $_SESSION['flash'] = '文件上传成功';
                    } else {
                        $_SESSION['flash'] = '文件上传失败';
                    }
                } else {
                    $_SESSION['flash'] = '文件格式不支持或大小超过10MB';
                }
            } else {
                $_SESSION['flash'] = '请选择要上传的文件';
            }
        }
        header('Location: index.php?page=files');
        exit;
    }

    if ($action === 'delete_file') {
        $id = (string)($_POST['id'] ?? '');
        $files = read_json_data('files', []);
        foreach ($files as $item) {
            if ((string)$item['id'] === $id) {
                $path = UPLOAD_DIR . DIRECTORY_SEPARATOR . basename((string)$item['stored_name']);
                if (file_exists($path)) {
                    unlink($path);
                }
            }
        }
        $files = array_values(array_filter($files, static function (array $item) use ($id): bool {
            return (string)$item['id'] !== $id;
        }));
        write_json_data('files', $files);
        $_SESSION['flash'] = '文件已删除';
        header('Location: index.php?page=files');
        exit;
    }
}

if (isset($_SESSION['flash'])) {
    $flash = (string)$_SESSION['flash'];
    unset($_SESSION['flash']);
}

$profile = read_json_data('profile', [
    'company_name' => APP_NAME,
    'slogan' => '让企业管理更简单',
    'phone' => '028-0000-0000',
    'email' => 'service@example.com',
    'address' => '成都市高新区创新大道123号',
    'about' => '成都123有限公司专注于企业数字化建设。',
]);
$announcements = read_json_data('announcements', []);
$customers = read_json_data('customers', []);
$files = read_json_data('files', []);

$stats = [
    'announcements' => count($announcements),
    'customers' => count($customers),
    'files' => count($files),
];
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理 - <?= APP_NAME ?></title>
    <style>
        *{box-sizing:border-box}
        body{margin:0;background:#f1f5f9;font-family:"Microsoft YaHei",Arial,sans-serif;color:#0f172a}
        .layout{display:grid;grid-template-columns:220px 1fr;min-height:100vh}
        .sidebar{background:#0f172a;color:#cbd5e1;padding:20px 14px}
        .logo{color:#fff;font-weight:700;font-size:18px;margin-bottom:20px}
        .menu a{
            display:block;color:#cbd5e1;text-decoration:none;padding:10px 12px;border-radius:8px;margin-bottom:6px
        }
        .menu a.active,.menu a:hover{background:#1d4ed8;color:#fff}
        .bottom-links{margin-top:20px;border-top:1px solid #334155;padding-top:12px}
        .bottom-links a{display:block;color:#94a3b8;text-decoration:none;padding:6px 12px}
        .main{padding:22px}
        .topbar{display:flex;justify-content:space-between;align-items:center;margin-bottom:16px}
        .title{font-size:22px;font-weight:700}
        .user{color:#475569}
        .flash{background:#dcfce7;color:#166534;border:1px solid #86efac;padding:10px 12px;border-radius:8px;margin-bottom:14px}
        .cards{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}
        .card{background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:16px}
        .card h3{margin:0 0 8px;color:#64748b;font-size:14px;font-weight:500}
        .card p{margin:0;font-size:30px;font-weight:700}
        .panel{background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:16px;margin-top:12px}
        .panel h2{margin:0 0 14px;font-size:18px}
        .form-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}
        .form-grid.full{grid-template-columns:1fr}
        label{display:block;font-size:13px;color:#475569;margin-bottom:4px}
        input,textarea,select{
            width:100%;padding:9px;border:1px solid #cbd5e1;border-radius:8px;font-size:14px;font-family:inherit
        }
        textarea{min-height:110px;resize:vertical}
        button{
            margin-top:10px;background:#2563eb;color:#fff;border:0;border-radius:8px;padding:10px 16px;cursor:pointer
        }
        table{width:100%;border-collapse:collapse}
        th,td{padding:10px;border-bottom:1px solid #e2e8f0;text-align:left;font-size:14px;vertical-align:top}
        th{color:#64748b;font-weight:600}
        .danger{background:#dc2626}
        .inline{display:inline}
        .empty{color:#94a3b8;padding:8px 0}
        @media (max-width:980px){
            .layout{grid-template-columns:1fr}
            .cards{grid-template-columns:1fr}
            .form-grid{grid-template-columns:1fr}
        }
    </style>
</head>
<body>
<div class="layout">
    <aside class="sidebar">
        <div class="logo"><?= APP_NAME ?></div>
        <nav class="menu">
            <a class="<?= $page === 'dashboard' ? 'active' : '' ?>" href="index.php?page=dashboard">数据看板</a>
            <a class="<?= $page === 'profile' ? 'active' : '' ?>" href="index.php?page=profile">企业信息</a>
            <a class="<?= $page === 'announcements' ? 'active' : '' ?>" href="index.php?page=announcements">公告管理</a>
            <a class="<?= $page === 'customers' ? 'active' : '' ?>" href="index.php?page=customers">客户管理</a>
            <a class="<?= $page === 'files' ? 'active' : '' ?>" href="index.php?page=files">文件中心</a>
        </nav>
        <div class="bottom-links">
            <a href="../index.php" target="_blank">访问官网</a>
            <a href="logout.php">退出登录</a>
        </div>
    </aside>
    <main class="main">
        <div class="topbar">
            <div class="title">后台管理中心</div>
            <div class="user">当前账号：<?= h((string)($_SESSION['admin_username'] ?? 'admin')) ?></div>
        </div>
        <?php if ($flash !== ''): ?>
            <div class="flash"><?= h($flash) ?></div>
        <?php endif; ?>

        <?php if ($page === 'dashboard'): ?>
            <div class="cards">
                <div class="card">
                    <h3>公告数量</h3>
                    <p><?= $stats['announcements'] ?></p>
                </div>
                <div class="card">
                    <h3>客户数量</h3>
                    <p><?= $stats['customers'] ?></p>
                </div>
                <div class="card">
                    <h3>上传文件</h3>
                    <p><?= $stats['files'] ?></p>
                </div>
            </div>
            <div class="panel">
                <h2>企业概览</h2>
                <table>
                    <tr><th width="120">公司名称</th><td><?= h((string)$profile['company_name']) ?></td></tr>
                    <tr><th>公司口号</th><td><?= h((string)$profile['slogan']) ?></td></tr>
                    <tr><th>联系电话</th><td><?= h((string)$profile['phone']) ?></td></tr>
                    <tr><th>联系邮箱</th><td><?= h((string)$profile['email']) ?></td></tr>
                    <tr><th>公司地址</th><td><?= h((string)$profile['address']) ?></td></tr>
                </table>
            </div>
        <?php endif; ?>

        <?php if ($page === 'profile'): ?>
            <div class="panel">
                <h2>企业信息设置</h2>
                <form method="post">
                    <input type="hidden" name="action" value="update_profile">
                    <div class="form-grid">
                        <div>
                            <label>公司名称</label>
                            <input name="company_name" value="<?= h((string)$profile['company_name']) ?>" required>
                        </div>
                        <div>
                            <label>公司口号</label>
                            <input name="slogan" value="<?= h((string)$profile['slogan']) ?>">
                        </div>
                        <div>
                            <label>联系电话</label>
                            <input name="phone" value="<?= h((string)$profile['phone']) ?>">
                        </div>
                        <div>
                            <label>联系邮箱</label>
                            <input name="email" type="email" value="<?= h((string)$profile['email']) ?>">
                        </div>
                    </div>
                    <div class="form-grid full">
                        <div>
                            <label>公司地址</label>
                            <input name="address" value="<?= h((string)$profile['address']) ?>">
                        </div>
                        <div>
                            <label>公司简介</label>
                            <textarea name="about"><?= h((string)$profile['about']) ?></textarea>
                        </div>
                    </div>
                    <button type="submit">保存企业信息</button>
                </form>
            </div>
        <?php endif; ?>

        <?php if ($page === 'announcements'): ?>
            <div class="panel">
                <h2>新增公告</h2>
                <form method="post">
                    <input type="hidden" name="action" value="add_announcement">
                    <div class="form-grid full">
                        <div>
                            <label>公告标题</label>
                            <input name="title" required>
                        </div>
                        <div>
                            <label>公告内容</label>
                            <textarea name="content" required></textarea>
                        </div>
                    </div>
                    <button type="submit">发布公告</button>
                </form>
            </div>
            <div class="panel">
                <h2>公告列表</h2>
                <?php if (count($announcements) === 0): ?>
                    <div class="empty">暂无公告</div>
                <?php else: ?>
                    <table>
                        <tr><th width="200">标题</th><th>内容</th><th width="180">发布时间</th><th width="100">操作</th></tr>
                        <?php foreach ($announcements as $item): ?>
                            <tr>
                                <td><?= h((string)$item['title']) ?></td>
                                <td><?= nl2br(h((string)$item['content'])) ?></td>
                                <td><?= h((string)$item['created_at']) ?></td>
                                <td>
                                    <form class="inline" method="post">
                                        <input type="hidden" name="action" value="delete_announcement">
                                        <input type="hidden" name="id" value="<?= h((string)$item['id']) ?>">
                                        <button class="danger" type="submit">删除</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </table>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <?php if ($page === 'customers'): ?>
            <div class="panel">
                <h2>新增客户</h2>
                <form method="post">
                    <input type="hidden" name="action" value="add_customer">
                    <div class="form-grid">
                        <div>
                            <label>客户名称</label>
                            <input name="name" required>
                        </div>
                        <div>
                            <label>联系人</label>
                            <input name="contact" required>
                        </div>
                        <div>
                            <label>套餐</label>
                            <select name="plan">
                                <option>标准版</option>
                                <option>专业版</option>
                                <option>旗舰版</option>
                            </select>
                        </div>
                        <div>
                            <label>状态</label>
                            <select name="status">
                                <option>跟进中</option>
                                <option>已签约</option>
                                <option>已暂停</option>
                            </select>
                        </div>
                    </div>
                    <button type="submit">新增客户</button>
                </form>
            </div>
            <div class="panel">
                <h2>客户列表</h2>
                <?php if (count($customers) === 0): ?>
                    <div class="empty">暂无客户数据</div>
                <?php else: ?>
                    <table>
                        <tr><th>客户名称</th><th>联系人</th><th>套餐</th><th>状态</th><th>创建时间</th><th width="100">操作</th></tr>
                        <?php foreach ($customers as $item): ?>
                            <tr>
                                <td><?= h((string)$item['name']) ?></td>
                                <td><?= h((string)$item['contact']) ?></td>
                                <td><?= h((string)$item['plan']) ?></td>
                                <td><?= h((string)$item['status']) ?></td>
                                <td><?= h((string)$item['created_at']) ?></td>
                                <td>
                                    <form class="inline" method="post">
                                        <input type="hidden" name="action" value="delete_customer">
                                        <input type="hidden" name="id" value="<?= h((string)$item['id']) ?>">
                                        <button class="danger" type="submit">删除</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </table>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <?php if ($page === 'files'): ?>
            <div class="panel">
                <h2>上传文件</h2>
                <form method="post" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="upload_file">
                    <div class="form-grid full">
                        <div>
                            <label>选择文件（支持文档、图片、压缩包，最大10MB）</label>
                            <input type="file" name="upload_file" required>
                        </div>
                    </div>
                    <button type="submit">上传文件</button>
                </form>
            </div>
            <div class="panel">
                <h2>文件列表</h2>
                <?php if (count($files) === 0): ?>
                    <div class="empty">暂无上传文件</div>
                <?php else: ?>
                    <table>
                        <tr><th>文件名</th><th>大小</th><th>上传时间</th><th width="180">下载</th><th width="100">操作</th></tr>
                        <?php foreach ($files as $item): ?>
                            <tr>
                                <td><?= h((string)$item['original_name']) ?></td>
                                <td><?= round(((int)$item['size']) / 1024, 2) ?> KB</td>
                                <td><?= h((string)$item['uploaded_at']) ?></td>
                                <td><a href="../uploads/<?= rawurlencode((string)$item['stored_name']) ?>" target="_blank">下载文件</a></td>
                                <td>
                                    <form class="inline" method="post">
                                        <input type="hidden" name="action" value="delete_file">
                                        <input type="hidden" name="id" value="<?= h((string)$item['id']) ?>">
                                        <button class="danger" type="submit">删除</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </table>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </main>
</div>
</body>
</html>
