<?php
require_once '../config.php';

$conn = get_db_connection();
$message = '';
$message_type = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    if ($action === 'add' || $action === 'edit') {
        $name = trim($_POST['name'] ?? '');
        $role_title = trim($_POST['role_title'] ?? '');
        $category_id = isset($_POST['category_id']) ? (int) $_POST['category_id'] : 0;
        $bio = trim($_POST['bio'] ?? '');
        $display_order = isset($_POST['display_order']) ? (int) $_POST['display_order'] : 0;
        $current_image = trim($_POST['current_image'] ?? '');
        $image_path = $current_image !== '' ? $current_image : null;

        if ($name === '' || $role_title === '' || $category_id <= 0) {
            $message = 'Name, Role, and Category are required.';
            $message_type = 'danger';
        } else {
            // Handle image upload
            if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                $file = $_FILES['image'];
                $allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
                $file_type = mime_content_type($file['tmp_name']);

                if (in_array($file_type, $allowed_types, true)) {
                    if ($file['size'] <= 5 * 1024 * 1024) { // 5MB
                        $upload_dir = dirname(__DIR__) . '/uploads/team/';
                        if (!is_dir($upload_dir)) {
                            mkdir($upload_dir, 0755, true);
                        }

                        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                        $filename = 'team-' . time() . '-' . uniqid() . '.' . $extension;
                        $filepath = $upload_dir . $filename;

                        if (move_uploaded_file($file['tmp_name'], $filepath)) {
                            $image_path = '/uploads/team/' . $filename;
                        }
                    }
                }
            }

            if ($action === 'add') {
                $stmt = $conn->prepare("INSERT INTO team_members (category_id, name, role_title, image, bio, display_order) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->bind_param('issssi', $category_id, $name, $role_title, $image_path, $bio, $display_order);
                if ($stmt->execute()) {
                    $message = 'Team member added successfully.';
                    $message_type = 'success';
                } else {
                    $message = 'Error adding team member: ' . $stmt->error;
                    $message_type = 'danger';
                }
                $stmt->close();
            } else {
                $id = (int) ($_POST['id'] ?? 0);
                if ($id > 0) {
                    $stmt = $conn->prepare("UPDATE team_members SET category_id = ?, name = ?, role_title = ?, image = ?, bio = ?, display_order = ? WHERE id = ?");
                    $stmt->bind_param('issssii', $category_id, $name, $role_title, $image_path, $bio, $display_order, $id);
                    if ($stmt->execute()) {
                        $message = 'Team member updated successfully.';
                        $message_type = 'success';
                    } else {
                        $message = 'Error updating team member: ' . $stmt->error;
                        $message_type = 'danger';
                    }
                    $stmt->close();
                }
            }
        }
    } elseif ($action === 'delete') {
        $id = (int) ($_POST['id'] ?? 0);
        if ($id > 0) {
            $stmt = $conn->prepare("DELETE FROM team_members WHERE id = ?");
            $stmt->bind_param('i', $id);
            if ($stmt->execute()) {
                $message = 'Team member deleted successfully.';
                $message_type = 'success';
            } else {
                $message = 'Error deleting team member: ' . $stmt->error;
                $message_type = 'danger';
            }
            $stmt->close();
        }
    }
}

// Fetch categories
$categories = [];
$cat_result = $conn->query("SELECT * FROM team_categories ORDER BY display_order ASC, name ASC");
if ($cat_result) {
    while ($row = $cat_result->fetch_assoc()) {
        $categories[] = $row;
    }
}

// Fetch team members
$team_members = [];
$members_result = $conn->query("SELECT m.*, c.name AS category_name 
    FROM team_members m 
    JOIN team_categories c ON m.category_id = c.id 
    ORDER BY c.display_order ASC, m.display_order ASC, m.id ASC");
if ($members_result) {
    while ($row = $members_result->fetch_assoc()) {
        $team_members[] = $row;
    }
}

// Member to edit
$edit_member = null;
if (isset($_GET['edit'])) {
    $edit_id = (int) $_GET['edit'];
    $stmt = $conn->prepare("SELECT * FROM team_members WHERE id = ?");
    $stmt->bind_param('i', $edit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result && $row = $result->fetch_assoc()) {
        $edit_member = $row;
    }
    $stmt->close();
}

$page_title = 'Team Management';
require_once 'includes/admin-header.php';
?>

<?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?>">
        <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
        <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title"><?php echo $edit_member ? 'Edit Team Member' : 'Add New Team Member'; ?></h2>
        <?php if ($edit_member): ?>
            <a href="team" class="btn btn-secondary btn-sm">Cancel</a>
        <?php endif; ?>
    </div>

    <form method="POST" action="" enctype="multipart/form-data">
        <input type="hidden" name="action" value="<?php echo $edit_member ? 'edit' : 'add'; ?>">
        <?php if ($edit_member): ?>
            <input type="hidden" name="id" value="<?php echo $edit_member['id']; ?>">
        <?php endif; ?>

        <div class="dashboard-grid">
            <div class="left-col">
                <div class="form-row">
                    <div class="form-group">
                        <label for="name">Full Name *</label>
                        <input type="text" id="name" name="name" class="form-control" required
                            value="<?php echo htmlspecialchars($edit_member['name'] ?? ''); ?>"
                            placeholder="e.g. John Smith">
                    </div>

                    <div class="form-group">
                        <label for="role_title">Role / Position *</label>
                        <input type="text" id="role_title" name="role_title" class="form-control" required
                            value="<?php echo htmlspecialchars($edit_member['role_title'] ?? ''); ?>"
                            placeholder="e.g. Lead Technician">
                    </div>
                </div>

                <div class="form-group">
                    <label for="bio">Short Bio</label>
                    <textarea id="bio" name="bio" class="form-control" style="min-height: 120px;"
                        placeholder="Tell us about this team member..."><?php echo htmlspecialchars($edit_member['bio'] ?? ''); ?></textarea>
                </div>
            </div>

            <div class="right-col">
                <div class="form-group">
                    <label for="category_id">Team Category *</label>
                    <select id="category_id" name="category_id" class="form-control" required>
                        <option value="">-- Select Category --</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>" <?php echo (isset($edit_member['category_id']) && $edit_member['category_id'] == $cat['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($cat['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label for="image">Profile Photo</label>
                    <?php if (!empty($edit_member['image'])): ?>
                        <div style="margin-bottom: 12px;">
                            <img src="<?php echo htmlspecialchars($edit_member['image']); ?>" alt="Current image"
                                style="width: 100%; border-radius: var(--radius-md); border: 1px solid var(--border);">
                        </div>
                    <?php endif; ?>
                    <input type="file" id="image" name="image" class="form-control" accept="image/*">
                    <input type="hidden" name="current_image"
                        value="<?php echo htmlspecialchars($edit_member['image'] ?? ''); ?>">
                </div>

                <div class="form-group">
                    <label for="display_order">Display Order</label>
                    <input type="number" id="display_order" name="display_order" class="form-control"
                        value="<?php echo $edit_member['display_order'] ?? 0; ?>" min="0">
                </div>

                <button type="submit" class="btn btn-primary" style="width: 100%; justify-content: center;">
                    <i class="fas fa-save"></i> <?php echo $edit_member ? 'Update Member' : 'Add Member'; ?>
                </button>
            </div>
        </div>
    </form>
</div>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Team Members (<?php echo count($team_members); ?>)</h2>
    </div>

    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>Photo</th>
                    <th>Name</th>
                    <th>Category</th>
                    <th>Role</th>
                    <th>Order</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($team_members)): ?>
                    <tr>
                        <td colspan="6" style="text-align: center; padding: 40px; color: var(--text-muted);">No team members
                            found. Add your first member above.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($team_members as $member): ?>
                        <tr>
                            <td style="width: 80px;">
                                <?php if (!empty($member['image'])): ?>
                                    <img src="<?php echo htmlspecialchars($member['image']); ?>" alt=""
                                        style="width: 50px; height: 50px; object-fit: cover; border-radius: 50%; border: 2px solid var(--border);">
                                <?php else: ?>
                                    <div
                                        style="width: 50px; height: 50px; background: var(--primary-light); color: var(--primary); border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 700;">
                                        <?php echo strtoupper(substr($member['name'], 0, 1)); ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div style="font-weight: 700;"><?php echo htmlspecialchars($member['name']); ?></div>
                            </td>
                            <td>
                                <span class="badge badge-info"><?php echo htmlspecialchars($member['category_name']); ?></span>
                            </td>
                            <td><?php echo htmlspecialchars($member['role_title']); ?></td>
                            <td><?php echo $member['display_order']; ?></td>
                            <td>
                                <div style="display: flex; gap: 8px;">
                                    <a href="?edit=<?php echo $member['id']; ?>" class="btn btn-secondary btn-sm">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <form method="POST" action="" style="display: inline;"
                                        onsubmit="return confirm('Are you sure you want to delete this team member?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?php echo $member['id']; ?>">
                                        <button type="submit" class="btn btn-danger btn-sm">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require_once 'includes/admin-footer.php'; ?>