<?php
session_start();
require_once 'db_config.php';

// লগইন চেক
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("location: login.php");
    exit;
}

// বর্তমান ভাষা নির্ধারণ (top_header.php এর সেশন অনুযায়ী)
$lang = isset($_SESSION['admin_lang']) ? $_SESSION['admin_lang'] : 'bn';

// অনুবাদ ডিকশনারি
$work_words = [
    'bn' => [
        'page_title' => 'রিসেন্ট ওয়ার্ক ম্যানেজমেন্ট',
        'add_new' => '+ নতুন রিসেন্ট ওয়ার্ক যোগ করুন',
        'update_info' => 'প্রজেক্ট আপডেট করুন',
        'proj_name' => 'প্রজেক্টের নাম',
        'proj_link' => 'ওয়েবসাইট লিংক (Optional)',
        'proj_img' => 'স্ক্রিনশট ছবি',
        'img_note' => '(পরিবর্তন করতে চাইলে নতুন ছবি দিন)',
        'save' => 'আপলোড করুন',
        'update' => 'আপডেট করুন',
        'cancel' => 'ক্যান্সেল',
        'th_img' => 'ছবি',
        'th_name' => 'নাম',
        'th_link' => 'লিংক',
        'th_status' => 'স্ট্যাটাস',
        'th_action' => 'অ্যাকশন',
        'visit' => 'ভিজিট',
        'active' => 'Active',
        'hidden' => 'Hidden',
        'confirm_delete' => 'আপনি কি নিশ্চিত?',
        'msg_add' => 'নতুন কাজ যুক্ত হয়েছে!',
        'msg_update' => 'আপডেট সফল হয়েছে!',
        'msg_delete' => 'ডিলিট হয়েছে!',
        'no_data' => 'কোনো প্রজেক্ট নেই'
    ],
    'en' => [
        'page_title' => 'Recent Work Management',
        'add_new' => '+ Add New Recent Work',
        'update_info' => 'Update Project',
        'proj_name' => 'Project Name',
        'proj_link' => 'Website Link (Optional)',
        'proj_img' => 'Screenshot Image',
        'img_note' => '(Upload new to change)',
        'save' => 'Upload Now',
        'update' => 'Update Now',
        'cancel' => 'Cancel',
        'th_img' => 'Image',
        'th_name' => 'Name',
        'th_link' => 'Link',
        'th_status' => 'Status',
        'th_action' => 'Action',
        'visit' => 'Visit',
        'active' => 'Active',
        'hidden' => 'Hidden',
        'confirm_delete' => 'Are you sure?',
        'msg_add' => 'New work added successfully!',
        'msg_update' => 'Updated successfully!',
        'msg_delete' => 'Deleted successfully!',
        'no_data' => 'No projects found'
    ]
];
$t = $work_words[$lang];

// ================= PHP লজিক শুরু ================= //

if (isset($_POST['save_work'])) {
    $id = $_POST['work_id'];
    $title = mysqli_real_escape_string($conn, $_POST['title']);
    $link = mysqli_real_escape_string($conn, $_POST['link']);

    $image_query = "";
    if (!empty($_FILES['work_image']['name'])) {
        $image = $_FILES['work_image']['name'];
        $upload_dir = __DIR__ . "/uploads/";
        if (!file_exists($upload_dir)) { mkdir($upload_dir, 0777, true); }
        $target = $upload_dir . basename($image);
        
        if (move_uploaded_file($_FILES['work_image']['tmp_name'], $target)) {
            $image_query = ", image='$image'";
            if($id) {
                $old_res = mysqli_query($conn, "SELECT image FROM recent_works WHERE id=$id");
                $old_row = mysqli_fetch_assoc($old_res);
                if($old_row && !empty($old_row['image']) && file_exists($upload_dir . $old_row['image'])) { 
                    unlink($upload_dir . $old_row['image']); 
                }
            }
        }
    }

    if ($id) {
        $sql = "UPDATE recent_works SET title='$title', link='$link' $image_query WHERE id=$id";
        $msg = $t['msg_update'];
    } else {
        $img_name = !empty($_FILES['work_image']['name']) ? $_FILES['work_image']['name'] : '';
        $sql = "INSERT INTO recent_works (title, link, image, status) VALUES ('$title', '$link', '$img_name', 1)";
        $msg = $t['msg_add'];
    }
    
    if(mysqli_query($conn, $sql)){
        echo "<script>alert('$msg'); window.location.href='recent_work_manage.php';</script>";
    } else {
        echo "<script>window.location.href='recent_work_manage.php';</script>";
    }
}

if (isset($_GET['toggle_status'])) {
    $id = intval($_GET['toggle_status']);
    $check_col = mysqli_query($conn, "SHOW COLUMNS FROM recent_works LIKE 'status'");
    if(mysqli_num_rows($check_col) > 0) {
        mysqli_query($conn, "UPDATE recent_works SET status = 1 - status WHERE id=$id");
    }
    echo "<script>window.location.href='recent_work_manage.php';</script>";
}

if (isset($_GET['delete_work'])) {
    $id = intval($_GET['delete_work']);
    $res = mysqli_query($conn, "SELECT image FROM recent_works WHERE id=$id");
    $row = mysqli_fetch_assoc($res);
    if($row && !empty($row['image'])) {
        $path = __DIR__ . "/uploads/" . $row['image'];
        if (file_exists($path)) { unlink($path); }
    }
    mysqli_query($conn, "DELETE FROM recent_works WHERE id=$id");
    echo "<script>alert('".$t['msg_delete']."'); window.location.href='recent_work_manage.php';</script>";
}

$edit_data = null;
if (isset($_GET['edit_work'])) {
    $id = intval($_GET['edit_work']);
    $res = mysqli_query($conn, "SELECT * FROM recent_works WHERE id=$id");
    $edit_data = mysqli_fetch_assoc($res);
}
?>

<!DOCTYPE html>
<html lang="<?php echo $lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $t['page_title']; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root { --primary: #2c3e50; --accent: #3498db; --bg: #f4f6f9; }
        * { margin:0; padding:0; box-sizing:border-box; font-family:'Segoe UI', sans-serif; }
        body { background: var(--bg); display:flex; min-height:100vh; }
        .main-content { margin-left:250px; width:calc(100% - 250px); transition: 0.3s; min-height: 100vh; }
        .content-body { padding: 30px; }

        /* ব্যাজ ও বাটন */
        .status-badge { padding: 5px 10px; border-radius: 20px; font-size: 0.8rem; color: #fff; font-weight: bold; }
        .status-active { background: #27ae60; }
        .status-inactive { background: #e74c3c; }

        .action-btn { padding: 6px 10px; border-radius: 4px; color: #fff; text-decoration: none; font-size: 0.85rem; margin-right: 5px; display: inline-block; }
        .btn-edit { background: #f39c12; } .btn-hide { background: #34495e; } .btn-show { background: #27ae60; } .btn-delete { background: #c0392b; }

        /* ফর্ম */
        .form-container { background: #fff; padding: 25px; border-radius: 8px; margin-bottom: 30px; border-left: 5px solid var(--accent); box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: 600; }
        .form-control { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; }
        .submit-btn { background: var(--accent); color: #fff; padding: 10px 25px; border: none; cursor: pointer; border-radius: 4px; font-size: 1rem; }

        /* টেবিল */
        table { width: 100%; border-collapse: collapse; background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
        th, td { padding: 15px; border-bottom: 1px solid #eee; text-align: left; vertical-align: middle; }
        th { background: #f8f9fa; color: var(--primary); }

        @media(max-width:768px){ .main-content{margin-left:0; width:100%;} }
    </style>
</head>
<body>

    <!-- ১. সাইডবার ইনক্লুড -->
    <?php include 'sidebar.php'; ?>

    <main class="main-content">
        
        <!-- ২. গ্লোবাল টপ হেডার ইনক্লুড -->
        <?php include 'top_header.php'; ?>

        <div class="content-body">
            <!-- অ্যাড / এডিট ফর্ম -->
            <div class="form-container">
                <h4><?php echo $edit_data ? $t['update_info'] : $t['add_new']; ?></h4>
                <br>
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="work_id" value="<?php echo $edit_data['id'] ?? ''; ?>">
                    
                    <div class="form-group">
                        <label><?php echo $t['proj_name']; ?></label>
                        <input type="text" name="title" class="form-control" value="<?php echo $edit_data['title'] ?? ''; ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label><?php echo $t['proj_link']; ?></label>
                        <input type="text" name="link" class="form-control" value="<?php echo $edit_data['link'] ?? ''; ?>">
                    </div>
                    
                    <div class="form-group">
                        <label><?php echo $t['proj_img']; ?> <?php echo $edit_data ? $t['img_note'] : ''; ?></label>
                        <input type="file" name="work_image" class="form-control" <?php echo $edit_data ? '' : 'required'; ?>>
                        <?php if($edit_data && $edit_data['image']): ?>
                            <img src="uploads/<?php echo $edit_data['image']; ?>" width="100" style="margin-top:10px; border-radius:5px;">
                        <?php endif; ?>
                    </div>

                    <button type="submit" name="save_work" class="submit-btn">
                        <?php echo $edit_data ? $t['update'] : $t['save']; ?>
                    </button>

                    <?php if($edit_data): ?>
                        <a href="recent_work_manage.php" style="margin-left:10px; color:red; text-decoration:none;"><?php echo $t['cancel']; ?></a>
                    <?php endif; ?>
                </form>
            </div>

            <!-- লিস্ট টেবিল -->
            <div style="overflow-x:auto;">
                <table>
                    <thead>
                        <tr>
                            <th><?php echo $t['th_img']; ?></th>
                            <th><?php echo $t['th_name']; ?></th>
                            <th><?php echo $t['th_link']; ?></th>
                            <th><?php echo $t['th_status']; ?></th>
                            <th><?php echo $t['th_action']; ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $res = mysqli_query($conn, "SELECT * FROM recent_works ORDER BY id DESC");
                        if(mysqli_num_rows($res) > 0) {
                            while($row = mysqli_fetch_assoc($res)){
                                $status = isset($row['status']) ? $row['status'] : 1;
                                $status_text = ($status == 1) ? $t['active'] : $t['hidden'];
                                $status_class = ($status == 1) ? 'status-active' : 'status-inactive';
                        ?>
                            <tr>
                                <td>
                                    <?php if($row['image']): ?>
                                        <img src="uploads/<?php echo $row['image']; ?>" width="80" height="50" style="object-fit: cover; border-radius: 5px;">
                                    <?php else: ?>
                                        <span style="color:red; font-size: 13px;">No Image</span>
                                    <?php endif; ?>
                                </td>
                                <td><b><?php echo htmlspecialchars($row['title']); ?></b></td>
                                <td>
                                    <?php if($row['link']): ?>
                                        <a href="<?php echo htmlspecialchars($row['link']); ?>" target="_blank" style="color:#3498db; text-decoration:none;"><i class="fas fa-external-link-alt"></i> <?php echo $t['visit']; ?></a>
                                    <?php else: ?>
                                        <span style="color:#999;">--</span>
                                    <?php endif; ?>
                                </td>
                                <td><span class="status-badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span></td>
                                <td>
                                    <a href="recent_work_manage.php?edit_work=<?php echo $row['id']; ?>" class="action-btn btn-edit"><i class="fas fa-edit"></i></a>
                                    
                                    <a href="recent_work_manage.php?toggle_status=<?php echo $row['id']; ?>" class="action-btn <?php echo ($status == 1) ? 'btn-hide' : 'btn-show'; ?>">
                                        <?php if($status == 1): ?><i class="fas fa-eye-slash"></i><?php else: ?><i class="fas fa-eye"></i><?php endif; ?>
                                    </a>
                                    
                                    <a href="recent_work_manage.php?delete_work=<?php echo $row['id']; ?>" class="action-btn btn-delete" onclick="return confirm('<?php echo $t['confirm_delete']; ?>')"><i class="fas fa-trash"></i></a>
                                </td>
                            </tr>
                        <?php } } else { ?>
                            <tr><td colspan="5" style="text-align:center; padding:20px;"><?php echo $t['no_data']; ?></td></tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</body>
</html>