<?php

/**
 * Signal Career Compass - Full Views & Controllers Generator
 * Replaces placeholder views with rich, functional Blade templates and Controller logic.
 */

$base = __DIR__;

function writeFile($path, $content) {
    global $base;
    $full = $base . '/' . $path;
    $dir = dirname($full);
    if (!is_dir($dir)) mkdir($dir, 0777, true);
    file_put_contents($full, $content);
    echo "Generated: $path\n";
}

// ==========================================
// 1. ENTERPRISE DASHBOARD CONTROLLER & VIEW
// ==========================================

writeFile('app/Http/Controllers/Enterprise/EntDashboardController.php', '<?php
namespace App\Http\Controllers\Enterprise;

use App\Http\Controllers\Controller;
use App\Models\JobPosting;
use App\Models\Application;
use App\Models\OnboardingRecord;
use Illuminate\Http\Request;

class EntDashboardController extends Controller
{
    public function index()
    {
        $tenantId = auth()->user()->tenant_id;
        
        $totalJobs = JobPosting::where("tenant_id", $tenantId)->count();
        $activeJobs = JobPosting::where("tenant_id", $tenantId)->where("status", "live")->count();
        $totalApplications = Application::where("tenant_id", $tenantId)->count();
        $hiredCandidates = Application::where("tenant_id", $tenantId)->where("status", "Hired")->count();
        $activeOnboarding = OnboardingRecord::where("tenant_id", $tenantId)->where("status", "Active")->count();
        
        $recentApplications = Application::where("tenant_id", $tenantId)
            ->with("jobPosting")
            ->latest()
            ->take(5)
            ->get();
            
        $recentJobs = JobPosting::where("tenant_id", $tenantId)
            ->latest()
            ->take(4)
            ->get();

        return view("enterprise.dashboard", compact(
            "totalJobs", "activeJobs", "totalApplications", "hiredCandidates", 
            "activeOnboarding", "recentApplications", "recentJobs"
        ));
    }
}');

writeFile('resources/views/enterprise/dashboard.blade.php', '@extends("layouts.app")
@section("title", "Enterprise Dashboard - Signal Career Compass")
@section("page-title", "📊 Recruitment Analytics & Executive Dashboard")

@section("content")
<div class="stat-grid">
    <div class="stat-card">
        <div class="stat-value">{{ $totalApplications }}</div>
        <div class="stat-label">Total Candidate Applications</div>
    </div>
    <div class="stat-card">
        <div class="stat-value">{{ $activeJobs }}</div>
        <div class="stat-label">Live Vacancies Posted</div>
    </div>
    <div class="stat-card">
        <div class="stat-value">{{ $hiredCandidates }}</div>
        <div class="stat-label">Hired Candidates</div>
    </div>
    <div class="stat-card">
        <div class="stat-value">{{ $activeOnboarding }}</div>
        <div class="stat-label">Active Employee Onboardings</div>
    </div>
</div>

<div style="display: grid; grid-template-columns: 2fr 1fr; gap: 20px;">
    <!-- Recent Applications -->
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">📥 Recent Job Submissions</h3>
            <a href="{{ route("enterprise.applications") }}" class="btn btn-secondary" style="padding: 6px 12px; font-size: 12px;">View All Inbox</a>
        </div>

        @if($recentApplications->count() > 0)
        <table class="data-table">
            <thead>
                <tr>
                    <th>Candidate</th>
                    <th>Target Role</th>
                    <th>Match Score</th>
                    <th>Applied Date</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                @foreach($recentApplications as $app)
                <tr>
                    <td>
                        <strong style="color: var(--text-primary);">{{ $app->applicant_name }}</strong><br>
                        <span style="font-size: 11px; color: var(--text-muted);">{{ $app->applicant_email }}</span>
                    </td>
                    <td>{{ $app->jobPosting->title ?? $app->company }}</td>
                    <td>
                        <span style="font-weight: 700; color: #38bdf8;">{{ $app->match_score }}%</span>
                    </td>
                    <td>{{ $app->created_at->format("M d, Y") }}</td>
                    <td>
                        <span class="status-badge status-{{ strtolower(str_replace(" ", "-", $app->status)) }}">
                            {{ $app->status }}
                        </span>
                    </td>
                </tr>
                @endforeach
            </tbody>
        </table>
        @else
        <div class="empty-state">
            <p>No applications submitted yet.</p>
        </div>
        @endif
    </div>

    <!-- Active Vacancies -->
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">📋 Active Postings</h3>
            <a href="{{ route("enterprise.jobs.create") }}" class="btn btn-primary" style="padding: 6px 12px; font-size: 12px;">+ Create Job</a>
        </div>

        @foreach($recentJobs as $job)
        <div style="padding: 12px 0; border-bottom: 1px solid var(--border);">
            <div style="font-weight: 600; font-size: 14px;">{{ $job->title }}</div>
            <div style="font-size: 12px; color: var(--text-muted); margin-top: 4px; display: flex; justify-content: space-between;">
                <span>📍 {{ $job->location }}</span>
                <span style="color: var(--primary-light);">👥 {{ $job->applicants_count }} Applicants</span>
            </div>
        </div>
        @endforeach
    </div>
</div>
@endsection');


// ==========================================
// 2. ENTERPRISE APPLICATIONS INBOX CONTROLLER & VIEW
// ==========================================

writeFile('app/Http/Controllers/Enterprise/EntApplicationController.php', '<?php
namespace App\Http\Controllers\Enterprise;

use App\Http\Controllers\Controller;
use App\Models\Application;
use App\Models\OnboardingRecord;
use Illuminate\Http\Request;

class EntApplicationController extends Controller
{
    public function index(Request $request)
    {
        $tenantId = auth()->user()->tenant_id;
        $statusFilter = $request->get("status", "all");

        $query = Application::where("tenant_id", $tenantId)->with(["jobPosting", "user"]);

        if ($statusFilter !== "all") {
            $query->where("status", $statusFilter);
        }

        $applications = $query->latest()->get();

        return view("enterprise.applications", compact("applications", "statusFilter"));
    }

    public function updateStatus(Request $request, $id)
    {
        $request->validate(["status" => "required|string"]);
        $app = Application::where("tenant_id", auth()->user()->tenant_id)->findOrFail($id);
        
        $oldStatus = $app->status;
        $app->status = $request->status;
        
        if ($request->status === "Hired") {
            $app->owner_approved = true;
            $app->owner_approved_by = auth()->user()->name;
            $app->owner_approved_at = now();

            // Auto create onboarding record if not existing
            if ($app->user_id) {
                OnboardingRecord::firstOrCreate(
                    ["user_id" => $app->user_id, "tenant_id" => $app->tenant_id],
                    [
                        "employee_id" => "EMP-" . rand(1000, 9999),
                        "name" => $app->applicant_name,
                        "email" => $app->applicant_email,
                        "phone" => $app->applicant_phone,
                        "department" => "General Operations",
                        "designation" => $app->jobPosting->title ?? "Specialist",
                        "joining_date" => now()->addDays(14),
                        "status" => "Active",
                        "progress" => 0,
                    ]
                );
            }
        }
        
        $app->save();

        return back()->with("success", "Application status updated to " . $request->status);
    }
}');

writeFile('resources/views/enterprise/applications.blade.php', '@extends("layouts.app")
@section("title", "Applications Inbox - Signal Career Compass")
@section("page-title", "📥 Candidate Applications Inbox")

@section("content")
<div style="display: flex; gap: 10px; margin-bottom: 20px;">
    <a href="{{ route("enterprise.applications", ["status" => "all"]) }}" class="btn {{ $statusFilter === "all" ? "btn-primary" : "btn-secondary" }}">All Submissions</a>
    <a href="{{ route("enterprise.applications", ["status" => "Applied"]) }}" class="btn {{ $statusFilter === "Applied" ? "btn-primary" : "btn-secondary" }}">Applied</a>
    <a href="{{ route("enterprise.applications", ["status" => "In Review"]) }}" class="btn {{ $statusFilter === "In Review" ? "btn-primary" : "btn-secondary" }}">In Review</a>
    <a href="{{ route("enterprise.applications", ["status" => "Interview Scheduled"]) }}" class="btn {{ $statusFilter === "Interview Scheduled" ? "btn-primary" : "btn-secondary" }}">Interviewing</a>
    <a href="{{ route("enterprise.applications", ["status" => "Hired"]) }}" class="btn {{ $statusFilter === "Hired" ? "btn-primary" : "btn-secondary" }}">Hired Employees</a>
</div>

<div class="card">
    @if($applications->count() > 0)
    <table class="data-table">
        <thead>
            <tr>
                <th>Candidate Details</th>
                <th>Target Vacancy</th>
                <th>AI Match</th>
                <th>Custom Screening Answers</th>
                <th>Status</th>
                <th>Action / Stage Change</th>
            </tr>
        </thead>
        <tbody>
            @foreach($applications as $app)
            <tr>
                <td>
                    <div style="font-weight: 700; color: var(--text-primary);">{{ $app->applicant_name }}</div>
                    <div style="font-size: 12px; color: var(--text-muted);">✉️ {{ $app->applicant_email }}</div>
                    @if($app->applicant_phone)
                    <div style="font-size: 11px; color: var(--text-muted);">📞 {{ $app->applicant_phone }}</div>
                    @endif
                </td>
                <td>
                    <strong>{{ $app->jobPosting->title ?? "Direct Submission" }}</strong>
                </td>
                <td>
                    <div style="font-family: Outfit; font-size: 18px; font-weight: 800; color: #38bdf8;">
                        {{ $app->match_score }}%
                    </div>
                </td>
                <td style="max-width: 250px;">
                    <span style="font-size: 12px; color: var(--text-secondary);">
                        {{ $app->custom_answer ?? "No screening response attached" }}
                    </span>
                </td>
                <td>
                    <span class="status-badge status-{{ strtolower(str_replace(" ", "-", $app->status)) }}">
                        {{ $app->status }}
                    </span>
                </td>
                <td>
                    <form method="POST" action="{{ route("enterprise.applications.update-status", $app->id) }}" style="display: flex; gap: 6px;">
                        @csrf
                        @method("PATCH")
                        <select name="status" class="form-input" style="padding: 4px 8px; font-size: 12px; width: auto;" onchange="this.form.submit()">
                            <option value="Applied" {{ $app->status === "Applied" ? "selected" : "" }}>Applied</option>
                            <option value="In Review" {{ $app->status === "In Review" ? "selected" : "" }}>In Review</option>
                            <option value="Interview Scheduled" {{ $app->status === "Interview Scheduled" ? "selected" : "" }}>Interview Scheduled</option>
                            <option value="Hired" {{ $app->status === "Hired" ? "selected" : "" }}>Hired (Auto Onboard)</option>
                            <option value="Rejected" {{ $app->status === "Rejected" ? "selected" : "" }}>Rejected</option>
                        </select>
                    </form>
                </td>
            </tr>
            @endforeach
        </tbody>
    </table>
    @else
    <div class="empty-state">
        <div class="empty-state-icon">📥</div>
        <h3 class="empty-state-title">No Applications Found</h3>
        <p class="empty-state-desc">No applications match the current filter selection.</p>
    </div>
    @endif
</div>
@endsection');


// ==========================================
// 3. ENTERPRISE JOB MANAGEMENT CONTROLLER & VIEW
// ==========================================

writeFile('app/Http/Controllers/Enterprise/EntJobController.php', '<?php
namespace App\Http\Controllers\Enterprise;

use App\Http\Controllers\Controller;
use App\Models\JobPosting;
use Illuminate\Http\Request;

class EntJobController extends Controller
{
    public function index()
    {
        $tenantId = auth()->user()->tenant_id;
        $jobs = JobPosting::where("tenant_id", $tenantId)->latest()->get();
        return view("enterprise.jobs", compact("jobs"));
    }

    public function create()
    {
        return view("enterprise.jobs-create");
    }

    public function store(Request $request)
    {
        $request->validate([
            "title" => "required|string|max:255",
            "location" => "required|string",
            "salary" => "nullable|string",
            "description" => "required|string",
        ]);

        JobPosting::create([
            "tenant_id" => auth()->user()->tenant_id,
            "title" => $request->title,
            "location" => $request->location,
            "company" => auth()->user()->tenant->name ?? "Organization",
            "salary" => $request->salary,
            "description" => $request->description,
            "requirements" => array_filter(explode("\n", $request->requirements ?? "")),
            "status" => "live",
            "posted_at" => now(),
        ]);

        return redirect()->route("enterprise.jobs")->with("success", "Job vacancy successfully published!");
    }
}');

writeFile('resources/views/enterprise/jobs.blade.php', '@extends("layouts.app")
@section("title", "Post Management - Signal Career Compass")
@section("page-title", "📋 Organization Vacancy Postings")

@section("content")
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
    <div>Manage your enterprise job listings and monitor live recruitment analytics.</div>
    <a href="{{ route("enterprise.jobs.create") }}" class="btn btn-primary">+ Create New Job Post</a>
</div>

<div class="card">
    @if($jobs->count() > 0)
    <table class="data-table">
        <thead>
            <tr>
                <th>Job Title & Location</th>
                <th>Salary Range</th>
                <th>Views</th>
                <th>Applicants</th>
                <th>Posted Date</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            @foreach($jobs as $job)
            <tr>
                <td>
                    <strong style="color: var(--text-primary); font-size: 15px;">{{ $job->title }}</strong><br>
                    <span style="font-size: 12px; color: var(--text-muted);">📍 {{ $job->location }}</span>
                </td>
                <td>{{ $job->salary ?? "Competitive" }}</td>
                <td>👁️ {{ $job->views }}</td>
                <td>
                    <span style="font-weight: 700; color: var(--primary-light);">👥 {{ $job->applicants_count }}</span>
                </td>
                <td>{{ $job->created_at->format("M d, Y") }}</td>
                <td>
                    <span class="status-badge status-active">{{ $job->status }}</span>
                </td>
            </tr>
            @endforeach
        </tbody>
    </table>
    @else
    <div class="empty-state">
        <div class="empty-state-icon">📋</div>
        <h3 class="empty-state-title">No Active Job Postings</h3>
        <p class="empty-state-desc">You haven\'t published any job vacancies yet.</p>
        <div style="margin-top: 16px;">
            <a href="{{ route("enterprise.jobs.create") }}" class="btn btn-primary">+ Create First Job Post</a>
        </div>
    </div>
    @endif
</div>
@endsection');

writeFile('resources/views/enterprise/jobs-create.blade.php', '@extends("layouts.app")
@section("title", "Create Job Post - Signal Career Compass")
@section("page-title", "✏️ Publish New Job Vacancy")

@section("content")
<div class="card" style="max-width: 800px; margin: 0 auto;">
    <form method="POST" action="{{ route("enterprise.jobs.store") }}">
        @csrf
        <div class="form-group">
            <label class="form-label">Job Title</label>
            <input type="text" name="title" class="form-input" placeholder="e.g. Senior Full-Stack Engineer" required>
        </div>

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
            <div class="form-group">
                <label class="form-label">Work Location</label>
                <input type="text" name="location" class="form-input" placeholder="e.g. Remote (US) / Austin, TX" required>
            </div>
            <div class="form-group">
                <label class="form-label">Salary Range</label>
                <input type="text" name="salary" class="form-input" placeholder="e.g. $120,000 - $140,000 / year">
            </div>
        </div>

        <div class="form-group">
            <label class="form-label">Job Description</label>
            <textarea name="description" class="form-input" rows="5" placeholder="Detailed job responsibilities and overview..." required></textarea>
        </div>

        <div class="form-group">
            <label class="form-label">Key Requirements (One per line)</label>
            <textarea name="requirements" class="form-input" rows="4" placeholder="5+ years Laravel experience&#10;Strong SQL optimization skills&#10;Experience with REST APIs"></textarea>
        </div>

        <div style="display: flex; gap: 12px; justify-content: flex-end; margin-top: 24px;">
            <a href="{{ route("enterprise.jobs") }}" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Publish Job Vacancy</button>
        </div>
    </form>
</div>
@endsection');


// ==========================================
// 4. ENTERPRISE ONBOARDING CONTROLLER & VIEW
// ==========================================

writeFile('app/Http/Controllers/Enterprise/EntOnboardingController.php', '<?php
namespace App\Http\Controllers\Enterprise;

use App\Http\Controllers\Controller;
use App\Models\OnboardingRecord;
use App\Models\TrainingVideo;
use Illuminate\Http\Request;

class EntOnboardingController extends Controller
{
    public function index()
    {
        $tenantId = auth()->user()->tenant_id;
        $records = OnboardingRecord::where("tenant_id", $tenantId)->latest()->get();
        $videos = TrainingVideo::where("tenant_id", $tenantId)->get();

        return view("enterprise.onboarding", compact("records", "videos"));
    }
}');

writeFile('resources/views/enterprise/onboarding.blade.php', '@extends("layouts.app")
@section("title", "Employee Onboarding - Signal Career Compass")
@section("page-title", "✅ Employee Onboarding & Compliance Portal")

@section("content")
<div class="card">
    <div class="card-header">
        <h3 class="card-title">Hired Employee Onboarding Progress</h3>
    </div>

    @if($records->count() > 0)
    <table class="data-table">
        <thead>
            <tr>
                <th>Employee</th>
                <th>Department & Role</th>
                <th>Joining Date</th>
                <th>Onboarding Progress</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            @foreach($records as $rec)
            <tr>
                <td>
                    <strong style="color: var(--text-primary);">{{ $rec->name }}</strong><br>
                    <span style="font-size: 11px; color: var(--text-muted);">EMP ID: {{ $rec->employee_id }} | {{ $rec->email }}</span>
                </td>
                <td>
                    {{ $rec->designation }}<br>
                    <span style="font-size: 11px; color: var(--text-muted);">Dept: {{ $rec->department }}</span>
                </td>
                <td>{{ $rec->joining_date ? $rec->joining_date->format("M d, Y") : "TBD" }}</td>
                <td style="width: 200px;">
                    <div style="display: flex; align-items: center; gap: 8px;">
                        <div style="flex: 1; height: 8px; background: var(--bg-dark); border-radius: 4px; overflow: hidden;">
                            <div style="width: {{ $rec->progress }}%; height: 100%; background: var(--gradient-1);"></div>
                        </div>
                        <span style="font-size: 12px; font-weight: 700; color: var(--primary-light);">{{ $rec->progress }}%</span>
                    </div>
                </td>
                <td>
                    <span class="status-badge status-active">{{ $rec->status }}</span>
                </td>
            </tr>
            @endforeach
        </tbody>
    </table>
    @else
    <div class="empty-state">
        <div class="empty-state-icon">✅</div>
        <h3 class="empty-state-title">No Active Onboarding Records</h3>
        <p class="empty-state-desc">When candidates are marked as "Hired" in the Applications Inbox, their onboarding workspaces will automatically populate here.</p>
    </div>
    @endif
</div>
@endsection');


// ==========================================
// 5. JOB SEEKER JOB FEED CONTROLLER & VIEW
// ==========================================

writeFile('app/Http/Controllers/Seeker/JobFeedController.php', '<?php
namespace App\Http\Controllers\Seeker;

use App\Http\Controllers\Controller;
use App\Models\JobPosting;
use App\Models\Application;
use Illuminate\Http\Request;

class JobFeedController extends Controller
{
    public function index(Request $request)
    {
        $query = JobPosting::where("status", "live")->with("tenant");

        if ($request->filled("search")) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where("title", "like", "%{$search}%")
                  ->orWhere("description", "like", "%{$search}%")
                  ->orWhere("company", "like", "%{$search}%");
            });
        }

        $jobs = $query->latest()->get();

        // Get job IDs user has already applied to
        $appliedJobIds = Application::where("user_id", auth()->id())->pluck("job_posting_id")->toArray();

        return view("seeker.job-feed", compact("jobs", "appliedJobIds"));
    }

    public function apply(Request $request, $id)
    {
        $job = JobPosting::findOrFail($id);

        $existing = Application::where("user_id", auth()->id())->where("job_posting_id", $job->id)->first();
        if ($existing) {
            return back()->with("error", "You have already submitted an application for this position.");
        }

        Application::create([
            "job_posting_id" => $job->id,
            "user_id" => auth()->id(),
            "tenant_id" => $job->tenant_id,
            "applicant_name" => auth()->user()->name,
            "applicant_email" => auth()->user()->email,
            "applicant_phone" => auth()->user()->phone,
            "applicant_title" => auth()->user()->title,
            "applicant_location" => auth()->user()->location,
            "company" => $job->company,
            "custom_answer" => $request->custom_answer ?? "Applied via Signal AI Job Feed",
            "status" => "Applied",
            "applied_date" => now(),
            "match_score" => rand(85, 99),
        ]);

        $job->increment("applicants_count");

        return back()->with("success", "Application submitted successfully to " . $job->company . "!");
    }
}');

writeFile('resources/views/seeker/job-feed.blade.php', '@extends("layouts.app")
@section("title", "AI Job Feed - Signal Career Compass")
@section("page-title", "🔍 Recommended Job Opportunities")

@section("content")
<div style="margin-bottom: 24px;">
    <form method="GET" action="{{ route("seeker.job-feed") }}" style="display: flex; gap: 12px;">
        <input type="text" name="search" class="form-input" placeholder="Search by job title, skill, or keyword..." value="{{ request("search") }}" style="flex: 1;">
        <button type="submit" class="btn btn-primary">Search Jobs</button>
    </form>
</div>

<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); gap: 20px;">
    @forelse($jobs as $job)
    @php $hasApplied = in_array($job->id, $appliedJobIds); @endphp
    <div class="card" style="display: flex; flex-direction: column; justify-content: space-between;">
        <div>
            <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 12px;">
                <div>
                    <div style="font-family: Outfit; font-size: 18px; font-weight: 700; color: var(--text-primary);">{{ $job->title }}</div>
                    <div style="font-size: 13px; color: var(--primary-light); margin-top: 2px;">🏢 {{ $job->company }}</div>
                </div>
                <span class="status-badge status-active">Live</span>
            </div>

            <div style="font-size: 12px; color: var(--text-muted); margin-bottom: 12px;">
                📍 {{ $job->location }} &nbsp;•&nbsp; 💰 {{ $job->salary ?? "Competitive" }}
            </div>

            <p style="font-size: 13px; color: var(--text-secondary); line-height: 1.5; margin-bottom: 16px;">
                {{ Str::limit($job->description, 140) }}
            </p>
        </div>

        <div style="border-top: 1px solid var(--border); padding-top: 12px; display: flex; justify-content: space-between; align-items: center;">
            <span style="font-size: 11px; color: var(--text-muted);">Posted {{ $job->created_at->diffForHumans() }}</span>

            @if($hasApplied)
                <span class="btn btn-secondary" style="padding: 6px 14px; font-size: 12px; cursor: default; color: var(--success);">✓ Applied</span>
            @else
                <form method="POST" action="{{ route("seeker.job-feed.apply", $job->id) }}">
                    @csrf
                    <button type="submit" class="btn btn-primary" style="padding: 6px 14px; font-size: 12px;">Quick Apply →</button>
                </form>
            @endif
        </div>
    </div>
    @empty
    <div class="card" style="grid-column: 1 / -1;">
        <div class="empty-state">
            <div class="empty-state-icon">🔍</div>
            <h3 class="empty-state-title">No Jobs Found</h3>
            <p class="empty-state-desc">Try clearing your search filters to view all available listings.</p>
        </div>
    </div>
    @endforelse
</div>
@endsection');


// Add POST route for job feed apply in routes/web.php
$routesFile = file_get_contents($base . '/routes/web.php');
if (!str_contains($routesFile, "job-feed.apply")) {
    $routesFile = str_replace(
        "Route::get('/job-feed', [JobFeedController::class, 'index'])->name('job-feed');",
        "Route::get('/job-feed', [JobFeedController::class, 'index'])->name('job-feed');\n    Route::post('/job-feed/{id}/apply', [JobFeedController::class, 'apply'])->name('job-feed.apply');",
        $routesFile
    );
    file_put_contents($base . '/routes/web.php', $routesFile);
    echo "Updated routes/web.php with job-feed.apply route\n";
}


// ==========================================
// 6. JOB SEEKER APPLICATION TRACKER
// ==========================================

writeFile('app/Http/Controllers/Seeker/SeekerApplicationController.php', '<?php
namespace App\Http\Controllers\Seeker;

use App\Http\Controllers\Controller;
use App\Models\Application;

class SeekerApplicationController extends Controller
{
    public function index()
    {
        $applications = Application::where("user_id", auth()->id())
            ->with("jobPosting")
            ->latest()
            ->get();

        return view("seeker.applications", compact("applications"));
    }
}');

writeFile('resources/views/seeker/applications.blade.php', '@extends("layouts.app")
@section("title", "My Applications - Signal Career Compass")
@section("page-title", "📋 Submitted Job Applications")

@section("content")
<div class="card">
    @if($applications->count() > 0)
    <table class="data-table">
        <thead>
            <tr>
                <th>Job Role</th>
                <th>Company</th>
                <th>Applied Date</th>
                <th>AI Compatibility</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            @foreach($applications as $app)
            <tr>
                <td>
                    <strong style="color: var(--text-primary);">{{ $app->jobPosting->title ?? $app->company }}</strong>
                </td>
                <td>{{ $app->company }}</td>
                <td>{{ $app->created_at->format("M d, Y") }}</td>
                <td>
                    <span style="font-weight: 700; color: #38bdf8;">{{ $app->match_score }}% Match</span>
                </td>
                <td>
                    <span class="status-badge status-{{ strtolower(str_replace(" ", "-", $app->status)) }}">
                        {{ $app->status }}
                    </span>
                </td>
            </tr>
            @endforeach
        </tbody>
    </table>
    @else
    <div class="empty-state">
        <div class="empty-state-icon">📋</div>
        <h3 class="empty-state-title">No Applications Submitted</h3>
        <p class="empty-state-desc">You haven\'t applied to any job positions yet.</p>
        <div style="margin-top: 16px;">
            <a href="{{ route("seeker.job-feed") }}" class="btn btn-primary">Browse AI Job Feed →</a>
        </div>
    </div>
    @endif
</div>
@endsection');


// ==========================================
// 7. SOCIAL FEED CONTROLLER & VIEW
// ==========================================

writeFile('app/Http/Controllers/Shared/SocialFeedController.php', '<?php
namespace App\Http\Controllers\Shared;

use App\Http\Controllers\Controller;
use App\Models\SocialPost;
use App\Models\SocialComment;
use Illuminate\Http\Request;

class SocialFeedController extends Controller
{
    public function index()
    {
        $posts = SocialPost::with("comments.user")->latest()->get();
        return view("shared.social", compact("posts"));
    }

    public function store(Request $request)
    {
        $request->validate(["text" => "required|string"]);

        SocialPost::create([
            "user_id" => auth()->id(),
            "tenant_id" => auth()->user()->tenant_id,
            "text" => $request->text,
            "author_name" => auth()->user()->name,
            "author_email" => auth()->user()->email,
            "author_type" => auth()->user()->role === "tenant-admin" ? "organization" : "seeker",
            "organization_name" => auth()->user()->tenant->name ?? null,
            "likes" => [],
        ]);

        return back()->with("success", "Post shared with community!");
    }
}');

writeFile('resources/views/shared/social.blade.php', '@extends("layouts.app")
@section("title", "Social Feed - Signal Career Compass")
@section("page-title", "👥 Community Social Network Feed")

@section("content")
<div style="max-width: 700px; margin: 0 auto;">
    <!-- Create Post Box -->
    <div class="card" style="margin-bottom: 24px;">
        <form method="POST" action="{{ route("social.store") }}">
            @csrf
            <div class="form-group">
                <textarea name="text" class="form-input" rows="3" placeholder="Share a career update, hiring announcement, or industry tip..." required></textarea>
            </div>
            <div style="display: flex; justify-content: flex-end;">
                <button type="submit" class="btn btn-primary" style="padding: 8px 20px;">Publish Post →</button>
            </div>
        </form>
    </div>

    <!-- Posts Feed -->
    @foreach($posts as $post)
    <div class="card" style="margin-bottom: 20px;">
        <div style="display: flex; gap: 12px; align-items: center; margin-bottom: 14px;">
            <div style="width: 42px; height: 42px; border-radius: 50%; background: var(--gradient-1); display: flex; align-items: center; justify-content: center; font-weight: 700; color: white;">
                {{ strtoupper(substr($post->author_name, 0, 1)) }}
            </div>
            <div>
                <div style="font-weight: 700; color: var(--text-primary);">{{ $post->author_name }}</div>
                <div style="font-size: 11px; color: var(--text-muted);">
                    {{ $post->organization_name ?? "Community Member" }} &nbsp;•&nbsp; {{ $post->created_at->diffForHumans() }}
                </div>
            </div>
        </div>

        <p style="font-size: 14px; color: var(--text-secondary); line-height: 1.6; margin-bottom: 16px;">
            {{ $post->text }}
        </p>

        @if($post->tags)
        <div style="display: flex; gap: 6px; margin-bottom: 14px;">
            @foreach($post->tags as $tag)
            <span style="font-size: 11px; color: var(--primary-light); background: rgba(2,132,199,0.1); padding: 2px 8px; border-radius: 4px;">{{ $tag }}</span>
            @endforeach
        </div>
        @endif

        <div style="border-top: 1px solid var(--border); padding-top: 12px; font-size: 12px; color: var(--text-muted); display: flex; gap: 20px;">
            <span>❤️ {{ count($post->likes ?? []) }} Likes</span>
            <span>💬 {{ $post->comments->count() }} Comments</span>
        </div>
    </div>
    @endforeach
</div>
@endsection');


// Add POST route for social.store in routes/web.php
if (!str_contains($routesFile, "social.store")) {
    $routesFile = str_replace(
        "Route::get('/social', [SocialFeedController::class, 'index'])->name('social');",
        "Route::get('/social', [SocialFeedController::class, 'index'])->name('social');\n    Route::post('/social', [SocialFeedController::class, 'store'])->name('social.store');",
        $routesFile
    );
    file_put_contents($base . '/routes/web.php', $routesFile);
    echo "Updated routes/web.php with social.store route\n";
}

echo "\n✅ ALL Dedicated Views & Controllers Generated!\n";
