<?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';

$words = [
    'bn' => [
        'page_title' => 'টিম ম্যানেজমেন্ট - অ্যাডমিন প্যানেল',
        'add_new' => '+ নতুন মেম্বার যোগ করুন',
        'update_info' => 'মেম্বার তথ্য আপডেট করুন',
        'name' => 'নাম',
        'role' => 'পদবী',
        'joining_date' => 'জয়েনিং ডেট',
        'fb_link' => 'ফেইসবুক লিংক',
        'li_link' => 'লিংকডইন লিংক',
        'git_link' => 'গিটহাব লিংক',
        'bio' => 'বায়ো / বিস্তারিত',
        'image' => 'ছবি',
        'img_change_note' => '(পরিবর্তন করতে চাইলে নতুন ছবি দিন)',
        'save' => 'সেভ করুন',
        'update' => 'আপডেট করুন',
        'cancel' => 'ক্যান্সেল',
        'th_img' => 'ছবি',
        'th_name_role' => 'নাম ও পদবী',
        'th_status' => 'স্ট্যাটাস',
        'th_action' => 'অ্যাকশন',
        'no_img' => 'ছবি নেই',
        'active' => 'Active',
        'hidden' => 'Hidden',
        'confirm_delete' => 'আপনি কি নিশ্চিত?',
        'msg_update' => 'মেম্বার আপডেট হয়েছে!',
        'msg_add' => 'নতুন মেম্বার যুক্ত হয়েছে!',
        'msg_delete' => 'মেম্বার ডিলিট হয়েছে!'
    ],
    'en' => [
        'page_title' => 'Team Management - Admin Panel',
        'add_new' => '+ Add New Member',
        'update_info' => 'Update Member Information',
        'name' => 'Name',
        'role' => 'Role / Designation',
        'joining_date' => 'Joining Date',
        'fb_link' => 'Facebook Link',
        'li_link' => 'LinkedIn Link',
        'git_link' => 'GitHub Link',
        'bio' => 'Bio / Details',
        'image' => 'Image',
        'img_change_note' => '(Upload new to change current image)',
        'save' => 'Save Now',
        'update' => 'Update Now',
        'cancel' => 'Cancel',
        'th_img' => 'Image',
        'th_name_role' => 'Name & Role',
        'th_status' => 'Status',
        'th_action' => 'Action',
        'no_img' => 'No Image',
        'active' => 'Active',
        'hidden' => 'Hidden',
        'confirm_delete' => 'Are you sure?',
        'msg_update' => 'Member updated successfully!',
        'msg_add' => 'New member added successfully!',
        'msg_delete' => 'Member deleted successfully!'
    ]
];
$t = $words[$lang];

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

if (isset($_POST['save_team'])) {
    $id = $_POST['team_id'];
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $role = mysqli_real_escape_string($conn, $_POST['role']);
    $bio = mysqli_real_escape_string($conn, $_POST['bio']);
    $joining_date = mysqli_real_escape_string($conn, $_POST['joining_date']);
    $fb = mysqli_real_escape_string($conn, $_POST['facebook']);
    $li = mysqli_real_escape_string($conn, $_POST['linkedin']);
    $git = mysqli_real_escape_string($conn, $_POST['github']);
    
    $image_query = ""; 
    if (!empty($_FILES['image']['name'])) {
        $image = $_FILES['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['image']['tmp_name'], $target)) {
            $image_query = ", image='$image'";
        }
    }

    if ($id) {
        $sql = "UPDATE team SET name='$name', role='$role', bio='$bio', joining_date='$joining_date', 
                facebook='$fb', linkedin='$li', github='$git' $image_query WHERE id=$id";
        $msg = $t['msg_update'];
    } else {
        $img_name = !empty($_FILES['image']['name']) ? $_FILES['image']['name'] : '';
        $sql = "INSERT INTO team (name, role, bio, joining_date, facebook, linkedin, github, image, status) 
                VALUES ('$name', '$role', '$bio', '$joining_date', '$fb', '$li', '$git', '$img_name', 1)";
        $msg = $t['msg_add'];
    }

    if(mysqli_query($conn, $sql)){
        echo "<script>alert('$msg'); window.location.href='team_manage.php';</script>";
    } else {
        echo "<script>alert('Error: " . mysqli_error($conn) . "');</script>";
    }
}

if (isset($_GET['toggle_status'])) {
    $id = intval($_GET['toggle_status']);
    mysqli_query($conn, "UPDATE team SET status = 1 - status WHERE id=$id");
    echo "<script>window.location.href='team_manage.php';</script>";
}

if (isset($_GET['delete_team'])) {
    $id = intval($_GET['delete_team']);
    $res = mysqli_query($conn, "SELECT image FROM team 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 team WHERE id=$id");
    echo "<script>alert('".$t['msg_delete']."'); window.location.href='team_manage.php';</script>";
}

$edit_data = null;
if (isset($_GET['edit_team'])) {
    $id = intval($_GET['edit_team']);
    $res = mysqli_query($conn, "SELECT * FROM team 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-row { display: flex; gap: 20px; flex-wrap: wrap; }
        .form-col { flex: 1; min-width: 250px; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; 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="team_id" value="<?php echo $edit_data['id'] ?? ''; ?>">
                    <div class="form-row">
                        <div class="form-col">
                            <div class="form-group">
                                <label><?php echo $t['name']; ?></label>
                                <input type="text" name="name" class="form-control" value="<?php echo $edit_data['name'] ?? ''; ?>" required>
                            </div>
                            <div class="form-group">
                                <label><?php echo $t['role']; ?></label>
                                <input type="text" name="role" class="form-control" value="<?php echo $edit_data['role'] ?? ''; ?>" required>
                            </div>
                            <div class="form-group">
                                <label><?php echo $t['joining_date']; ?></label>
                                <input type="date" name="joining_date" class="form-control" value="<?php echo $edit_data['joining_date'] ?? ''; ?>">
                            </div>
                        </div>
                        <div class="form-col">
                            <div class="form-group">
                                <label><?php echo $t['fb_link']; ?></label>
                                <input type="text" name="facebook" class="form-control" value="<?php echo $edit_data['facebook'] ?? ''; ?>">
                            </div>
                            <div class="form-group">
                                <label><?php echo $t['li_link']; ?></label>
                                <input type="text" name="linkedin" class="form-control" value="<?php echo $edit_data['linkedin'] ?? ''; ?>">
                            </div>
                            <div class="form-group">
                                <label><?php echo $t['git_link']; ?></label>
                                <input type="text" name="github" class="form-control" value="<?php echo $edit_data['github'] ?? ''; ?>">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label><?php echo $t['bio']; ?></label>
                        <textarea name="bio" class="form-control" rows="3"><?php echo $edit_data['bio'] ?? ''; ?></textarea>
                    </div>
                    <div class="form-group">
                        <label><?php echo $t['image']; ?> <?php echo $edit_data ? $t['img_change_note'] : ''; ?></label>
                        <input type="file" name="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="50" style="margin-top:5px; border-radius:5px;">
                        <?php endif; ?>
                    </div>
                    <button type="submit" name="save_team" class="submit-btn"><?php echo $edit_data ? $t['update'] : $t['save']; ?></button>
                    <?php if($edit_data): ?>
                        <a href="team_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_role']; ?></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 team ORDER BY id DESC");
                        while ($row = mysqli_fetch_assoc($res)) {
                            $status_text = ($row['status'] == 1) ? $t['active'] : $t['hidden'];
                            $status_class = ($row['status'] == 1) ? 'status-active' : 'status-inactive';
                        ?>
                        <tr>
                            <td>
                                <?php if(!empty($row['image'])): ?>
                                    <img src="uploads/<?php echo $row['image']; ?>" width="50" height="50" style="border-radius:50%; object-fit:cover;">
                                <?php else: ?>
                                    <span style="font-size:0.8rem; color:#999;"><?php echo $t['no_img']; ?></span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <b><?php echo htmlspecialchars($row['name']); ?></b><br>
                                <small style="color:#777;"><?php echo htmlspecialchars($row['role']); ?></small>
                            </td>
                            <td><span class="status-badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span></td>
                            <td>
                                <a href="team_manage.php?edit_team=<?php echo $row['id']; ?>" class="action-btn btn-edit"><i class="fas fa-edit"></i></a>
                                <a href="team_manage.php?toggle_status=<?php echo $row['id']; ?>" class="action-btn <?php echo ($row['status'] == 1) ? 'btn-hide' : 'btn-show'; ?>">
                                    <?php if($row['status'] == 1): ?><i class="fas fa-eye-slash"></i><?php else: ?><i class="fas fa-eye"></i><?php endif; ?>
                                </a>
                                <a href="team_manage.php?delete_team=<?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 } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</body>
</html>