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

// Handle Delete with cascade
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    // Fetch company to delete images
    $stmt = $conn->prepare("SELECT logo, banner FROM companies WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        if (!empty($row['logo']) && file_exists('../' . $row['logo']) && strpos($row['logo'], 'uploads/') === 0) {
            @unlink('../' . $row['logo']);
        }
        if (!empty($row['banner']) && file_exists('../' . $row['banner']) && strpos($row['banner'], 'uploads/') === 0) {
            @unlink('../' . $row['banner']);
        }
    }
    
    // Delete associated founders and directors images & records
    $f_res = $conn->query("SELECT photo FROM founders WHERE company_id = $id");
    if ($f_res) {
        while ($f = $f_res->fetch_assoc()) {
            if (!empty($f['photo']) && file_exists('../' . $f['photo']) && strpos($f['photo'], 'uploads/') === 0) {
                @unlink('../' . $f['photo']);
            }
        }
    }
    $d_res = $conn->query("SELECT photo FROM directors WHERE company_id = $id");
    if ($d_res) {
        while ($d = $d_res->fetch_assoc()) {
            if (!empty($d['photo']) && file_exists('../' . $d['photo']) && strpos($d['photo'], 'uploads/') === 0) {
                @unlink('../' . $d['photo']);
            }
        }
    }
    
    $conn->query("DELETE FROM founders WHERE company_id = $id");
    $conn->query("DELETE FROM directors WHERE company_id = $id");
    $conn->query("DELETE FROM companies WHERE id = $id");
    header("Location: manage_customers.php?msg=deleted");
    exit;
}

// Handle Publish / Unpublish Toggle
if (isset($_GET['toggle_status'])) {
    $id = intval($_GET['toggle_status']);
    $stmt = $conn->prepare("SELECT status FROM companies 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 companies SET status = ? WHERE id = ?");
    $update_stmt->bind_param("si", $new_status, $id);
    $update_stmt->execute();
    header("Location: manage_customers.php?msg=status_updated");
    exit;
}

// Search and Filter logic
$search = trim($_GET['search'] ?? '');
$status_filter = trim($_GET['status'] ?? '');
$industry_filter = trim($_GET['industry'] ?? '');

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

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

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

if ($industry_filter !== '') {
    $where_clauses[] = "industry = ?";
    $params[] = $industry_filter;
    $types .= 's';
}

$sql = "SELECT c.*, 
        (SELECT COUNT(*) FROM founders WHERE company_id = c.id) as founder_count,
        (SELECT COUNT(*) FROM directors WHERE company_id = c.id) as director_count
        FROM companies c";

if (!empty($where_clauses)) {
    $sql .= " WHERE " . implode(" AND ", $where_clauses);
}
$sql .= " ORDER BY c.display_order ASC, c.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 distinct industries for filter dropdown
$ind_res = $conn->query("SELECT DISTINCT industry FROM companies WHERE industry IS NOT NULL AND industry != '' ORDER BY industry ASC");
$industries = [];
if ($ind_res) {
    while ($r = $ind_res->fetch_assoc()) {
        $industries[] = $r['industry'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Companies - 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>
        .company-thumb {
            width: 48px;
            height: 48px;
            object-fit: contain;
            background: #fff;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
            padding: 2px;
        }
        .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;
        }
        .action-btn-group .btn {
            padding: 4px 8px;
            font-size: 13px;
        }
    </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" class="active"><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"><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="job_applications.php"><i class="fas fa-briefcase me-2"></i> Job Applications</a></li>
            <li><a href="contact_messages.php"><i class="fas fa-envelope me-2"></i> Messages</a></li>
            <li><a href="manage_credentials.php"><i class="fas fa-user-cog me-2"></i> Manage Credentials</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-building text-primary me-2"></i> Company / Customer Profiles</h2>
                <small class="text-muted">Manage companies, founders, directors and customer showcases</small>
            </div>
            <div class="d-flex gap-2">
                <a href="company_add.php" class="btn btn-primary"><i class="fas fa-plus me-1"></i> Add Company</a>
                <a href="founder_add.php" class="btn btn-outline-primary"><i class="fas fa-user-plus me-1"></i> Add Founder</a>
                <a href="director_add.php" class="btn btn-outline-primary"><i class="fas fa-user-plus me-1"></i> Add Director</a>
            </div>
        </div>

        <?php if(isset($_GET['msg']) && $_GET['msg'] === 'deleted'): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle me-2"></i> Company and all associated profiles 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" role="alert">
                <i class="fas fa-info-circle me-2"></i> Status updated successfully.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Search & Filter Form -->
        <div class="filter-card">
            <form method="GET" action="manage_customers.php" class="row g-3 align-items-center">
                <div class="col-md-4">
                    <div class="input-group">
                        <span class="input-group-text bg-white"><i class="fas fa-search text-muted"></i></span>
                        <input type="text" name="search" class="form-control" placeholder="Search by name, legal name..." value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                </div>
                <div class="col-md-3">
                    <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-3">
                    <select name="industry" class="form-select">
                        <option value="">All Industries</option>
                        <?php foreach($industries as $ind): ?>
                            <option value="<?php echo htmlspecialchars($ind); ?>" <?php echo $industry_filter === $ind ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($ind); ?>
                            </option>
                        <?php endforeach; ?>
                    </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 !== '' || $industry_filter !== ''): ?>
                        <a href="manage_customers.php" class="btn btn-outline-secondary" title="Reset Filters"><i class="fas fa-redo"></i></a>
                    <?php endif; ?>
                </div>
            </form>
        </div>

        <!-- Companies 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;">Logo</th>
                        <th>Company Name</th>
                        <th>Type / Industry</th>
                        <th>Founders</th>
                        <th>Directors</th>
                        <th>Status</th>
                        <th>Created</th>
                        <th style="width: 220px;" 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['logo'])): ?>
                                    <img src="../<?php echo htmlspecialchars($row['logo']); ?>" alt="" class="company-thumb" onerror="this.src='https://via.placeholder.com/48?text=Logo'">
                                <?php else: ?>
                                    <div class="company-thumb d-flex align-items-center justify-content-center fw-bold text-primary">
                                        <?php echo strtoupper(substr($row['company_name'], 0, 1)); ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="fw-bold text-dark"><?php echo htmlspecialchars($row['company_name']); ?></div>
                                <?php if(!empty($row['legal_name'])): ?>
                                    <small class="text-muted"><?php echo htmlspecialchars($row['legal_name']); ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div><span class="badge bg-light text-dark border"><?php echo htmlspecialchars($row['company_type'] ?: 'Company'); ?></span></div>
                                <small class="text-muted"><i class="fas fa-industry me-1"></i><?php echo htmlspecialchars($row['industry'] ?: 'General'); ?></small>
                            </td>
                            <td>
                                <a href="manage_founders.php?company_id=<?php echo $row['id']; ?>" class="badge bg-primary-subtle text-primary text-decoration-none">
                                    <i class="fas fa-user-tie me-1"></i> <?php echo $row['founder_count']; ?> Founder(s)
                                </a>
                            </td>
                            <td>
                                <a href="manage_directors.php?company_id=<?php echo $row['id']; ?>" class="badge bg-info-subtle text-info text-decoration-none">
                                    <i class="fas fa-users-cog me-1"></i> <?php echo $row['director_count']; ?> Director(s)
                                </a>
                            </td>
                            <td>
                                <a href="manage_customers.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><small class="text-muted"><?php echo date('d M Y', strtotime($row['created_at'])); ?></small></td>
                            <td>
                                <div class="d-flex gap-1 justify-content-center action-btn-group flex-wrap">
                                    <a href="/bm/company.php?id=<?php echo $row['id']; ?>" target="_blank" class="btn btn-sm btn-outline-info" title="View Public Profile">
                                        <i class="fas fa-external-link-alt"></i>
                                    </a>
                                    <a href="company_edit.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-warning text-dark" title="Edit Company">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="founder_add.php?company_id=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-primary" title="Add Founder to this Company">
                                        <i class="fas fa-user-tie"></i>+
                                    </a>
                                    <a href="director_add.php?company_id=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-secondary" title="Add Director to this Company">
                                        <i class="fas fa-users"></i>+
                                    </a>
                                    <a href="manage_customers.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['company_name'])); ?>? All associated founders and directors will also be deleted.')" title="Delete Company">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="9" class="text-center py-5">
                                <div class="text-muted">
                                    <i class="fas fa-building fa-3x mb-3 text-secondary"></i>
                                    <h5>No companies found</h5>
                                    <p>Get started by clicking the "Add Company" button above.</p>
                                    <a href="company_add.php" class="btn btn-primary mt-2"><i class="fas fa-plus me-1"></i> Add First Company</a>
                                </div>
                            </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>
