<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit;
}
include '../includes/db.php';

// Handle Delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    // Remove image if local
    $stmt = $conn->prepare("SELECT photo FROM directors WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        if (!empty($row['photo']) && file_exists('../' . $row['photo']) && strpos($row['photo'], 'uploads/') === 0) {
            @unlink('../' . $row['photo']);
        }
    }
    $del = $conn->prepare("DELETE FROM directors WHERE id = ?");
    $del->bind_param("i", $id);
    $del->execute();
    header("Location: manage_directors.php?msg=deleted");
    exit;
}

// Handle Status Toggle
if (isset($_GET['toggle_status'])) {
    $id = intval($_GET['toggle_status']);
    $stmt = $conn->prepare("SELECT status FROM directors WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $curr = $stmt->get_result()->fetch_assoc()['status'] ?? 'Published';
    $new_status = ($curr === 'Published') ? 'Draft' : 'Published';
    
    $update_stmt = $conn->prepare("UPDATE directors SET status = ? WHERE id = ?");
    $update_stmt->bind_param("si", $new_status, $id);
    $update_stmt->execute();
    header("Location: manage_directors.php?msg=status_updated");
    exit;
}

// Filters
$company_filter = intval($_GET['company_id'] ?? 0);
$status_filter = trim($_GET['status'] ?? '');
$type_filter = trim($_GET['director_type'] ?? '');
$search = trim($_GET['search'] ?? '');

$where_clauses = [];
$params = [];
$types = '';

if ($company_filter > 0) {
    $where_clauses[] = "d.company_id = ?";
    $params[] = $company_filter;
    $types .= 'i';
}

if ($status_filter !== '' && in_array($status_filter, ['Published', 'Draft', 'Inactive'])) {
    $where_clauses[] = "d.status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

if ($type_filter !== '') {
    $where_clauses[] = "d.director_type = ?";
    $params[] = $type_filter;
    $types .= 's';
}

if ($search !== '') {
    $where_clauses[] = "(d.name LIKE ? OR d.designation LIKE ? OR c.company_name LIKE ?)";
    $s_term = "%$search%";
    $params[] = $s_term;
    $params[] = $s_term;
    $params[] = $s_term;
    $types .= 'sss';
}

$sql = "SELECT d.*, c.company_name FROM directors d LEFT JOIN companies c ON d.company_id = c.id";
if (!empty($where_clauses)) {
    $sql .= " WHERE " . implode(" AND ", $where_clauses);
}
$sql .= " ORDER BY d.display_order ASC, d.created_at DESC";

if (!empty($params)) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query($sql);
}

// Fetch all companies for filter dropdown
$comp_list = $conn->query("SELECT id, company_name FROM companies ORDER BY company_name ASC");

// Fetch distinct director types
$type_res = $conn->query("SELECT DISTINCT director_type FROM directors WHERE director_type IS NOT NULL AND director_type != '' ORDER BY director_type ASC");
$director_types = [];
if ($type_res) {
    while ($tr = $type_res->fetch_assoc()) {
        $director_types[] = $tr['director_type'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Directors - Admin Panel</title>
    <link rel="shortcut icon" href="/bm/BM LOGO.jpg" type="image/jpeg">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="dashboard.css">
    <style>
        .director-thumb {
            width: 48px;
            height: 48px;
            object-fit: cover;
            border-radius: 50%;
            border: 2px solid #e2e8f0;
        }
        .filter-card {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            padding: 18px;
            margin-bottom: 20px;
        }
        .status-badge-Published { background-color: #10b981; color: white; }
        .status-badge-Draft { background-color: #f59e0b; color: white; }
        .status-badge-Inactive { background-color: #6b7280; color: white; }
        .table-responsive {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.06);
            overflow: hidden;
        }
    </style>
</head>
<body>
    <div class="sidebar d-flex flex-column flex-shrink-0 p-3 text-white">
        <a href="dashboard.php" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none">
            <span class="fs-4 fw-bold">Admin Panel</span>
        </a>
        <hr>
        <ul class="nav nav-pills flex-column mb-auto">
            <li><a href="dashboard.php"><i class="fas fa-tachometer-alt me-2"></i> Dashboard</a></li>
            <li><a href="manage_services.php"><i class="fas fa-tools me-2"></i> Manage Services</a></li>
            <li><a href="manage_customers.php"><i class="fas fa-building me-2"></i> Manage Companies</a></li>
            <li><a href="manage_founders.php"><i class="fas fa-user-tie me-2"></i> Manage Founders</a></li>
            <li><a href="manage_directors.php" class="active"><i class="fas fa-users-cog me-2"></i> Manage Directors</a></li>
            <li><a href="manage_pages.php"><i class="fas fa-file-alt me-2"></i> Manage Content</a></li>
            <li><a href="manage_blogs.php"><i class="fas fa-blog me-2"></i> Manage Blogs</a></li>
            <li><a href="logout.php" class="text-danger"><i class="fas fa-sign-out-alt me-2"></i> Logout</a></li>
        </ul>
    </div>

    <div class="content">
        <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
            <div>
                <h2 class="mb-0 fw-bold"><i class="fas fa-users-cog text-primary me-2"></i> Manage Directors</h2>
                <small class="text-muted">Manage board of directors, executive directors, and independent directors</small>
            </div>
            <a href="director_add.php<?php echo ($company_filter > 0) ? '?company_id='.$company_filter : ''; ?>" class="btn btn-primary">
                <i class="fas fa-plus me-1"></i> Add Director
            </a>
        </div>

        <?php if(isset($_GET['msg']) && $_GET['msg'] === 'deleted'): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle me-2"></i> Director deleted successfully.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php elseif(isset($_GET['msg']) && $_GET['msg'] === 'status_updated'): ?>
            <div class="alert alert-info alert-dismissible fade show">
                <i class="fas fa-info-circle me-2"></i> Director status updated successfully.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php elseif(isset($_GET['msg']) && $_GET['msg'] === 'added'): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle me-2"></i> Director added successfully.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php elseif(isset($_GET['msg']) && $_GET['msg'] === 'updated'): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle me-2"></i> Director updated successfully.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Filters -->
        <div class="filter-card">
            <form method="GET" action="manage_directors.php" class="row g-3 align-items-center">
                <div class="col-md-3">
                    <input type="text" name="search" class="form-control" placeholder="Search by name, title..." value="<?php echo htmlspecialchars($search); ?>">
                </div>
                <div class="col-md-3">
                    <select name="company_id" class="form-select">
                        <option value="">All Companies</option>
                        <?php if($comp_list): while($c = $comp_list->fetch_assoc()): ?>
                            <option value="<?php echo $c['id']; ?>" <?php echo ($company_filter == $c['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($c['company_name']); ?>
                            </option>
                        <?php endwhile; endif; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <select name="director_type" class="form-select">
                        <option value="">All Types</option>
                        <?php foreach($director_types as $dt): ?>
                            <option value="<?php echo htmlspecialchars($dt); ?>" <?php echo ($type_filter === $dt) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($dt); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <select name="status" class="form-select">
                        <option value="">All Statuses</option>
                        <option value="Published" <?php echo $status_filter === 'Published' ? 'selected' : ''; ?>>Published</option>
                        <option value="Draft" <?php echo $status_filter === 'Draft' ? 'selected' : ''; ?>>Draft</option>
                        <option value="Inactive" <?php echo $status_filter === 'Inactive' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>
                <div class="col-md-2 d-flex gap-2">
                    <button type="submit" class="btn btn-dark w-100"><i class="fas fa-filter me-1"></i> Filter</button>
                    <?php if($search !== '' || $status_filter !== '' || $company_filter > 0 || $type_filter !== ''): ?>
                        <a href="manage_directors.php" class="btn btn-outline-secondary" title="Reset Filters"><i class="fas fa-redo"></i></a>
                    <?php endif; ?>
                </div>
            </form>
        </div>

        <!-- Table -->
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-dark">
                    <tr>
                        <th style="width: 50px;">Order</th>
                        <th style="width: 70px;">Photo</th>
                        <th>Director Name</th>
                        <th>Company</th>
                        <th>Designation / Type</th>
                        <th>Status</th>
                        <th style="width: 160px;" class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($result && $result->num_rows > 0): ?>
                        <?php while($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td class="text-center fw-bold text-muted"><?php echo $row['display_order']; ?></td>
                            <td>
                                <?php if(!empty($row['photo'])): ?>
                                    <img src="../<?php echo htmlspecialchars($row['photo']); ?>" alt="" class="director-thumb" onerror="this.src='https://via.placeholder.com/48?text=User'">
                                <?php else: ?>
                                    <div class="director-thumb d-flex align-items-center justify-content-center bg-light text-primary fw-bold">
                                        <?php echo strtoupper(substr($row['name'], 0, 1)); ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="fw-bold text-dark"><?php echo htmlspecialchars($row['name']); ?></div>
                                <?php if(!empty($row['education'])): ?>
                                    <small class="text-muted"><i class="fas fa-graduation-cap me-1"></i><?php echo htmlspecialchars($row['education']); ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="badge bg-light text-dark border">
                                    <i class="fas fa-building me-1 text-primary"></i> <?php echo htmlspecialchars($row['company_name'] ?: 'Unassigned'); ?>
                                </span>
                            </td>
                            <td>
                                <div class="fw-semibold"><?php echo htmlspecialchars($row['designation'] ?: 'Director'); ?></div>
                                <?php if(!empty($row['director_type'])): ?>
                                    <span class="badge bg-secondary-subtle text-secondary border"><?php echo htmlspecialchars($row['director_type']); ?></span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="manage_directors.php?toggle_status=<?php echo $row['id']; ?>" 
                                   class="badge status-badge-<?php echo $row['status']; ?> text-decoration-none"
                                   title="Click to toggle publish status">
                                    <?php echo htmlspecialchars($row['status']); ?>
                                </a>
                            </td>
                            <td class="text-center">
                                <div class="d-flex gap-1 justify-content-center">
                                    <a href="director_edit.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-warning text-dark" title="Edit Director">
                                        <i class="fas fa-edit"></i> Edit
                                    </a>
                                    <a href="manage_directors.php?delete=<?php echo $row['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete <?php echo htmlspecialchars(addslashes($row['name'])); ?>?')" title="Delete Director">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" class="text-center py-5 text-muted">
                                <i class="fas fa-users-cog fa-3x mb-3 text-secondary"></i>
                                <h5>No directors found</h5>
                                <a href="director_add.php" class="btn btn-primary mt-2"><i class="fas fa-plus me-1"></i> Add First Director</a>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
