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

// Auto-Repair Database Schema (Run once check)
try {
    $check = $conn->query("SHOW COLUMNS FROM job_applications LIKE 'status'");
    if ($check->num_rows == 0) {
        $conn->query("ALTER TABLE job_applications ADD COLUMN status ENUM('active', 'bin') DEFAULT 'active'");
    }
    
    $check_fav = $conn->query("SHOW COLUMNS FROM job_applications LIKE 'is_favorite'");
    if ($check_fav->num_rows == 0) {
        $conn->query("ALTER TABLE job_applications ADD COLUMN is_favorite TINYINT(1) DEFAULT 0");
    }

    $check_pin = $conn->query("SHOW COLUMNS FROM job_applications LIKE 'pincode'");
    if ($check_pin->num_rows == 0) {
        $conn->query("ALTER TABLE job_applications ADD COLUMN pincode VARCHAR(10)");
    }
} catch (Exception $e) {
    // Ignore error if column exists or permission issue, simply try to proceed
}

// Handle Actions
if (isset($_GET['action']) && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $action = $_GET['action'];

    if ($action == 'bin') {
        // Move to Bin (Soft Delete)
        $conn->query("UPDATE job_applications SET status='bin' WHERE id=$id");
        header("Location: job_applications.php?msg=binned");
        exit;
    } elseif ($action == 'restore') {
        // Restore from Bin
        $conn->query("UPDATE job_applications SET status='active' WHERE id=$id");
        header("Location: job_applications.php?view=bin&msg=restored");
        exit;
    } elseif ($action == 'delete') {
        // Permanent Delete
        $stmt = $conn->prepare("SELECT resume_path FROM job_applications WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($res->num_rows > 0) {
            $row = $res->fetch_assoc();
            $file_path = "../" . $row['resume_path'];
            if (file_exists($file_path) && !empty($row['resume_path'])) {
                unlink($file_path);
            }
            $conn->query("DELETE FROM job_applications WHERE id=$id");
        }
        header("Location: job_applications.php?view=bin&msg=deleted");
        exit;
    } elseif ($action == 'fav') {
        // Toggle Favorite
        $conn->query("UPDATE job_applications SET is_favorite = NOT is_favorite WHERE id=$id");
        // Return to previous view
        $view = isset($_GET['view']) ? $_GET['view'] : 'active';
        header("Location: job_applications.php?view=$view");
        exit;
    }
}

// Filter Logic
$view = isset($_GET['view']) ? $_GET['view'] : 'active';
$where_clause = "WHERE status = 'active'";
if ($view == 'bin') {
    $where_clause = "WHERE status = 'bin'";
} elseif ($view == 'favorites') {
    $where_clause = "WHERE status = 'active' AND is_favorite = 1";
}

$result = $conn->query("SELECT * FROM job_applications $where_clause ORDER BY created_at DESC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Job Applications</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">
</head>
<body>
    <div class="sidebar d-flex flex-column flex-shrink-0 p-3 text-white" style="width: 280px;">
        <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">Admin Panel</span>
        </a>
        <hr>
        <ul class="nav nav-pills flex-column mb-auto">
            <li class="nav-item">
                <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_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" class="active"><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="wp/post.php"><i class="fas fa-pen me-2"></i> Add New Post</a>
            </li>
            <li>
                <a href="#"><i class="fas fa-newspaper me-2"></i> Blog</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-3">
            <h2>Job Applications</h2>
            <div class="btn-group">
                <a href="job_applications.php?view=active" class="btn btn-outline-primary <?php echo ($view == 'active') ? 'active' : ''; ?>">All Applications</a>
                <a href="job_applications.php?view=favorites" class="btn btn-outline-warning <?php echo ($view == 'favorites') ? 'active' : ''; ?>">Favorites</a>
                <a href="job_applications.php?view=bin" class="btn btn-outline-danger <?php echo ($view == 'bin') ? 'active' : ''; ?>">Recycle Bin</a>
            </div>
        </div>
        
        <?php if(isset($_GET['msg'])): ?>
            <div class="alert alert-success">
                <?php 
                    if($_GET['msg'] == 'binned') echo "Moved to Bin.";
                    elseif($_GET['msg'] == 'restored') echo "Application Restored.";
                    elseif($_GET['msg'] == 'deleted') echo "Deleted Permanently.";
                    

        
                ?>
                
            </div>
        <?php endif; ?>

        <div class="table-responsive">
            <table class="table table-bordered table-striped align-middle">
                <thead class="table-dark">
                    <tr>
                        <th>sl.no.</th>
                        <th>Fav</th>
                        <th>Name</th>
                        <th>Contact Info</th>
                        <th>Address Details & Pin</th>
                        <th>Resume</th>
                        <th>Date</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    if ($result->num_rows > 0):
                        $i = 1; // Sequential Counter
                        while($row = $result->fetch_assoc()): 
                    ?>
                    <tr>
                        <td><?php echo $i++; ?></td>
                        <td class="text-center">
                            <a href="job_applications.php?action=fav&id=<?php echo $row['id']; ?>&view=<?php echo $view; ?>" class="text-decoration-none">
                                <i class="fas fa-star fav-star <?php echo ($row['is_favorite']) ? 'active' : ''; ?>"></i>
                            </a>
                        </td>
                        <td>
                            <strong><?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?></strong>
                        </td>
                        <td>
                            <small><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($row['email']); ?></small><br>
                            <small><i class="fas fa-phone"></i> <?php echo htmlspecialchars($row['mobile']); ?></small>
                        </td>
                        <td>
                            <?php 
                            echo htmlspecialchars($row['address']) . ' ' . 
                                 htmlspecialchars($row['district'] . ', ' . $row['state']) . ' ' . 
                                 htmlspecialchars($row['pincode']); 
                            ?>
                        </td>
                        <td>
                            <a href="../<?php echo htmlspecialchars($row['resume_path']); ?>" target="_blank" class="btn btn-sm btn-outline-info">View</a>
                        </td>
                        <td>
                            <small><?php echo date('d M, Y h:i A', strtotime($row['created_at'])); ?></small>
                        </td>
                        <td>
                            <?php if($view == 'bin'): ?>
                                <a href="job_applications.php?action=restore&id=<?php echo $row['id']; ?>" class="btn btn-sm btn-success" title="Restore"><i class="fas fa-undo"></i></a>
                                <a href="job_applications.php?action=delete&id=<?php echo $row['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete permanently?');" title="Delete Forever"><i class="fas fa-trash"></i></a>
                            <?php else: ?>
                                <a href="job_applications.php?action=bin&id=<?php echo $row['id']; ?>" class="btn btn-sm btn-warning" title="Move to Bin"><i class="fas fa-trash-alt"></i></a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="8" class="text-center">No applications found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>
