<?php
$admin_page = 'haberler';
$admin_title = 'Haberler';
include 'admin_header.php';

$action = $_GET['action'] ?? 'list';
$id = (int)($_GET['id'] ?? 0);
$msg = ''; $msg_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title    = trim($_POST['title'] ?? '');
    $excerpt  = trim($_POST['excerpt'] ?? '');
    $content  = trim($_POST['content'] ?? '');
    $status   = $_POST['status'] ?? 'active';
    $slug     = slugify($title);

    $image = $_POST['existing_image'] ?? '';
    if (!empty($_FILES['image']['name'])) {
        $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext,['jpg','jpeg','png','webp'])) {
            $fname = uniqid('news_').'.'.$ext;
            if (move_uploaded_file($_FILES['image']['tmp_name'], '../assets/uploads/'.$fname)) $image = $fname;
        }
    }
    try {
        if ($_POST['edit_id'] ?? 0) {
            $eid=(int)$_POST['edit_id'];
            db()->prepare("UPDATE vs_news SET title=?,slug=?,excerpt=?,content=?,image=?,status=? WHERE id=?")->execute([$title,$slug,$excerpt,$content,$image,$status,$eid]);
            $msg='Güncellendi.'; $msg_type='success';
        } else {
            $check=db()->prepare("SELECT COUNT(*) FROM vs_news WHERE slug=?"); $check->execute([$slug]);
            if($check->fetchColumn()) $slug.='-'.time();
            db()->prepare("INSERT INTO vs_news (title,slug,excerpt,content,image,status) VALUES (?,?,?,?,?,?)")->execute([$title,$slug,$excerpt,$content,$image,$status]);
            $msg='Eklendi.'; $msg_type='success';
        }
        $action='list';
    } catch(Exception $e){ $msg='Hata.'; $msg_type='error'; }
}

if ($action==='delete' && $id) { db()->prepare("DELETE FROM vs_news WHERE id=?")->execute([$id]); $msg='Silindi.'; $msg_type='success'; $action='list'; }

$edit=null;
if ($action==='edit' && $id) { $s=db()->prepare("SELECT * FROM vs_news WHERE id=?"); $s->execute([$id]); $edit=$s->fetch(PDO::FETCH_ASSOC); if(!$edit) $action='list'; }

$news=[];
if ($action==='list') { try { $news=db()->query("SELECT * FROM vs_news ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC); } catch(Exception $e){} }
?>
<?php if($msg): ?><div class="alert alert-<?= $msg_type ?>"><?= clean($msg) ?></div><?php endif; ?>
<?php if($action==='list'): ?>
<div class="page-header"><h1>Haberler</h1><a href="?action=add" class="btn btn-primary">+ Yeni Haber</a></div>
<div class="admin-card">
    <table>
        <thead><tr><th>Başlık</th><th>Tarih</th><th>Durum</th><th>İşlemler</th></tr></thead>
        <tbody>
        <?php foreach($news as $n): ?>
        <tr>
            <td><strong><?= clean($n['title']) ?></strong></td>
            <td style="color:var(--gray);font-size:12px;"><?= date('d.m.Y',strtotime($n['created_at'])) ?></td>
            <td><span class="badge <?= $n['status']==='active'?'badge-green':'badge-gray' ?>"><?= $n['status']==='active'?'Aktif':'Taslak' ?></span></td>
            <td><a href="?action=edit&id=<?= $n['id'] ?>" class="btn btn-outline btn-sm">Düzenle</a> <a href="?action=delete&id=<?= $n['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Sil?')">Sil</a></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php else: ?>
<div class="page-header"><h1><?= $action==='edit'?'Düzenle':'Yeni Haber' ?></h1><a href="?action=list" style="color:var(--gray);font-size:13px;">← Geri</a></div>
<div class="admin-card" style="padding:28px;max-width:700px;">
    <form method="POST" enctype="multipart/form-data">
        <?php if($action==='edit'): ?><input type="hidden" name="edit_id" value="<?= $edit['id'] ?>"><?php endif; ?>
        <div style="display:flex;flex-direction:column;gap:16px;">
            <div class="admin-form-group"><label>Başlık *</label><input type="text" name="title" required value="<?= clean($edit['title']??'') ?>"></div>
            <div class="admin-form-group"><label>Özet</label><textarea name="excerpt"><?= clean($edit['excerpt']??'') ?></textarea></div>
            <div class="admin-form-group"><label>İçerik</label><textarea name="content" rows="8"><?= clean($edit['content']??'') ?></textarea></div>
            <div class="admin-form-group">
                <label>Görsel</label>
                <?php if(!empty($edit['image'])): ?><img src="/volker/assets/uploads/<?= clean($edit['image']) ?>" style="width:100%;max-height:160px;object-fit:cover;border-radius:4px;margin-bottom:8px;"><input type="hidden" name="existing_image" value="<?= clean($edit['image']) ?>"><?php endif; ?>
                <input type="file" name="image" accept="image/*">
            </div>
            <div class="admin-form-group"><label>Durum</label><select name="status"><option value="active" <?= ($edit['status']??'active')==='active'?'selected':'' ?>>Aktif</option><option value="draft">Taslak</option></select></div>
            <button type="submit" class="btn btn-primary">Kaydet</button>
        </div>
    </form>
</div>
<?php endif; ?>
<?php include 'admin_footer.php'; ?>
