<?php
include '../includes/db.php';
 include 'header.php';
// Handle Add/Edit/Delete
if(isset($_POST['add_card'])){
    $type = $conn->real_escape_string($_POST['type']);
    $description = $conn->real_escape_string($_POST['description']);
    
    // Handle image upload
    $image = '';
    if(isset($_FILES['image']) && $_FILES['image']['name'] != ''){
        $targetDir = "../uploads/cards/"; // Upload folder
        if(!is_dir($targetDir)) mkdir($targetDir, 0777, true);
        $imageName = time() . '_' . basename($_FILES['image']['name']);
        move_uploaded_file($_FILES['image']['tmp_name'], $targetDir . $imageName);
        $image = 'uploads/cards/' . $imageName; // store full path in DB
    }

    $conn->query("INSERT INTO client_cards (type, description, image) VALUES ('$type', '$description', '$image')");
    header("Location: cards.php");
    exit;
}

if(isset($_POST['edit_card'])){
    $id = intval($_POST['id']);
    $type = $conn->real_escape_string($_POST['type']);
    $description = $conn->real_escape_string($_POST['description']);
    
    $card = $conn->query("SELECT image FROM client_cards WHERE id=$id")->fetch_assoc();
    $image = $card['image'];

    if(isset($_FILES['image']) && $_FILES['image']['name'] != ''){
        $targetDir = "../uploads/cards/";
        if(!is_dir($targetDir)) mkdir($targetDir, 0777, true);
        $imageName = time() . '_' . basename($_FILES['image']['name']);
        move_uploaded_file($_FILES['image']['tmp_name'], $targetDir . $imageName);
        $image = 'uploads/cards/' . $imageName; // store full path in DB
    }

    $conn->query("UPDATE client_cards SET type='$type', description='$description', image='$image' WHERE id=$id");
    header("Location: cards.php");
    exit;
}

if(isset($_GET['delete'])){
    $id = intval($_GET['delete']);
    
    // Delete image file
    $card = $conn->query("SELECT image FROM client_cards WHERE id=$id")->fetch_assoc();
    if($card['image'] != '' && file_exists("../" . $card['image'])){
        unlink("../" . $card['image']);
    }
    
    $conn->query("DELETE FROM client_cards WHERE id=$id");
    header("Location: cards.php");
    exit;
}

// Fetch all cards
$cards = $conn->query("SELECT * FROM client_cards ORDER BY id DESC");
?>

<h2>Manage Client Cards</h2>

<!-- Add New Card Form -->
<h3>Add New Card</h3>
<form method="post" enctype="multipart/form-data">
    <label>Type:</label><br>
    <input type="text" name="type" required><br><br>

    <label>Description:</label><br>
    <textarea name="description" class="tinymce"></textarea><br><br>

    <label>Image:</label><br>
    <input type="file" name="image" required><br><br>

    <button type="submit" name="add_card">Add Card</button>
</form>

<hr>

<h3>Existing Cards</h3>
<table border="1" cellpadding="10" cellspacing="0">
    <tr>
        <th>ID</th>
        <th>Type</th>
        <th>Description</th>
        <th>Image</th>
        <th>Actions</th>
    </tr>
    <?php while($card = $cards->fetch_assoc()): ?>
    <tr>
        <td><?= $card['id'] ?></td>
        <td><?= htmlspecialchars($card['type']) ?></td>
        <td><?= substr(strip_tags($card['description']),0,50) ?>...</td>
        <td>
            <?php if($card['image'] != ''): ?>
                <img src="../<?= $card['image'] ?>" width="100">
            <?php else: ?>
                No Image
            <?php endif; ?>
        </td>
        <td>
            <a href="cards.php?edit=<?= $card['id'] ?>">Edit</a> | 
            <a href="cards.php?delete=<?= $card['id'] ?>" onclick="return confirm('Delete this card?')">Delete</a>
        </td>
    </tr>
    <?php endwhile; ?>
</table>

<?php
// Edit Form
if(isset($_GET['edit'])){
    $id = intval($_GET['edit']);
    $card = $conn->query("SELECT * FROM client_cards WHERE id=$id")->fetch_assoc();
?>
<hr>
<h3>Edit Card ID <?= $card['id'] ?></h3>
<form method="post" enctype="multipart/form-data">
    <input type="hidden" name="id" value="<?= $card['id'] ?>">
    
    <label>Type:</label><br>
    <input type="text" name="type" value="<?= htmlspecialchars($card['type']) ?>" required><br><br>

    <label>Description:</label><br>
    <textarea name="description" class="tinymce"><?= htmlspecialchars($card['description']) ?></textarea><br><br>

    <label>Image (leave blank to keep current):</label><br>
    <input type="file" name="image"><br>
    <?php if($card['image'] != ''): ?>
        <img src="../<?= $card['image'] ?>" width="100"><br><br>
    <?php endif; ?>

    <button type="submit" name="edit_card">Update Card</button>
</form>
<?php } ?>

<!-- TinyMCE -->
<script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
  selector: 'textarea.tinymce',
  height: 300,
  menubar: false,
  plugins: [
    'advlist autolink lists link image charmap print preview anchor',
    'searchreplace visualblocks code fullscreen',
    'insertdatetime media table paste code help wordcount'
  ],
  toolbar: 'undo redo | formatselect | bold italic backcolor | \
  alignleft aligncenter alignright alignjustify | \
  bullist numlist outdent indent | removeformat | help'
});
</script>

<?php include '../includes/footer.php'; ?>

<style>
body {
    font-family: Arial, sans-serif;
    background: #f5f5f5;
    padding: 20px;
    color: #333;
}
h2, h3 { color: #444; }
form {
    background: #fff;
    padding: 20px;
    margin-bottom: 30px;
    border-radius: 8px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}
form input[type="text"],
form input[type="file"],
form textarea {
    width: 100%;
    padding: 10px;
    margin-top: 6px;
    margin-bottom: 15px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
}
form button {
    background-color: #28a745;
    color: white;
    padding: 12px 25px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 16px;
}
form button:hover { background-color: #218838; }
table {
    width: 100%;
    border-collapse: collapse;
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}
table th, table td {
    padding: 12px 15px;
    text-align: left;
}
table th { background-color: #007bff; color: white; font-weight: bold; }
table tr:nth-child(even) { background-color: #f9f9f9; }
table img { border-radius: 5px; }
a { color: #007bff; text-decoration: none; }
a:hover { text-decoration: underline; }
hr { margin: 40px 0; border: 0; border-top: 1px solid #ccc; }
</style>
