#!/bin/bash
# ============================================================
# SaaS Accounting — Phase 6 Deploy Script
# Run: bash deploy_phase6.sh
# From: ~/public_html/saas-accounting/
# ============================================================
set -e
cd ~/public_html/saas-accounting

echo "=== 1. Writing Employee Model ==="
cat > app/Models/Employee.php << 'PHPEOF'
<?php
namespace App\Models;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\SoftDeletes;
class Employee extends BaseModel {
    use SoftDeletes;
    protected $fillable = ['company_id','parent_id','code','name','designation','department','email','phone','joining_date','bank_account','is_active'];
    protected $casts = ['is_active'=>'boolean','joining_date'=>'date'];
    public function company()  { return $this->belongsTo(Company::class); }
    public function parent()   { return $this->belongsTo(Employee::class,'parent_id'); }
    public function children() { return $this->hasMany(Employee::class,'parent_id'); }
}
PHPEOF

echo "=== 2. Writing OtherName Model ==="
cat > app/Models/OtherName.php << 'PHPEOF'
<?php
namespace App\Models;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\SoftDeletes;
class OtherName extends BaseModel {
    use SoftDeletes;
    protected $table = 'other_names';
    protected $fillable = ['company_id','code','name','type','phone','email','address','is_active'];
    protected $casts = ['is_active'=>'boolean'];
    public function company() { return $this->belongsTo(Company::class); }
}
PHPEOF

echo "=== 3. Adding parent_id to Item Model ==="
sed -i "s/'company_id','category_id','code','name'/'company_id','parent_id','category_id','code','name'/" app/Models/Item.php
grep -q "public function parent()" app/Models/Item.php || sed -i "s/public function company().*belongsTo(Company::class); }/public function company()          { return \$this->belongsTo(Company::class); }\n    public function parent()           { return \$this->belongsTo(Item::class,'parent_id'); }\n    public function children()         { return \$this->hasMany(Item::class,'parent_id'); }/" app/Models/Item.php

echo "=== 4. Writing EmployeesController ==="
cat > app/Http/Controllers/Company/Masters/EmployeesController.php << 'PHPEOF'
<?php
namespace App\Http\Controllers\Company\Masters;
use App\Http\Controllers\Controller;
use App\Models\{AuditLog, Employee};
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
class EmployeesController extends Controller {
    public function index(Request $request) {
        $this->gate();
        $cid = auth()->user()->company_id;
        $q = Employee::withoutGlobalScopes()->where('company_id',$cid)->whereNull('deleted_at');
        if ($request->filled('search')) { $s=$request->search; $q->where(fn($x)=>$x->where('name','like',"%$s%")->orWhere('code','like',"%$s%")->orWhere('email','like',"%$s%")); }
        if ($request->filled('status')) { $q->where('is_active',$request->status==='active'); }
        $employees = $q->orderBy('name')->paginate(25)->withQueryString();
        $stats = ['total'=>Employee::withoutGlobalScopes()->where('company_id',$cid)->whereNull('deleted_at')->count(),'active'=>Employee::withoutGlobalScopes()->where('company_id',$cid)->whereNull('deleted_at')->where('is_active',true)->count()];
        return view('masters.employees.index',compact('employees','stats'));
    }
    public function create() {
        $this->gate('create');
        $cid = auth()->user()->company_id;
        $parents = Employee::withoutGlobalScopes()->where('company_id',$cid)->whereNull('deleted_at')->where('is_active',true)->orderBy('name')->get(['id','name','code']);
        return view('masters.employees.create',compact('parents'));
    }
    public function store(Request $request) {
        $this->gate('create');
        $cid = auth()->user()->company_id;
        $v = $request->validate(['code'=>['nullable','string','max:30',Rule::unique('employees')->where(fn($q)=>$q->where('company_id',$cid)->whereNull('deleted_at'))],'name'=>'required|string|max:150','designation'=>'nullable|string|max:100','department'=>'nullable|string|max:100','email'=>'nullable|email|max:150','phone'=>'nullable|string|max:30','joining_date'=>'nullable|date','bank_account'=>'nullable|string|max:50','parent_id'=>'nullable|integer']);
        $emp = Employee::withoutGlobalScopes()->create(array_merge($v,['company_id'=>$cid,'is_active'=>true]));
        AuditLog::record('create','employees',(string)$emp->id,null,['name'=>$emp->name],"Employee created: {$emp->name}");
        return redirect()->route('masters.employees.index')->with('success',"Employee '{$emp->name}' created.");
    }
    public function edit(Employee $employee) {
        $this->gate('edit'); $this->sc($employee);
        $cid = auth()->user()->company_id;
        $parents = Employee::withoutGlobalScopes()->where('company_id',$cid)->whereNull('deleted_at')->where('id','!=',$employee->id)->where('is_active',true)->orderBy('name')->get(['id','name','code']);
        return view('masters.employees.edit',compact('employee','parents'));
    }
    public function update(Request $request, Employee $employee) {
        $this->gate('edit'); $this->sc($employee);
        $cid = auth()->user()->company_id;
        $v = $request->validate(['code'=>['nullable','string','max:30',Rule::unique('employees')->where(fn($q)=>$q->where('company_id',$cid)->whereNull('deleted_at'))->ignore($employee->id)],'name'=>'required|string|max:150','designation'=>'nullable|string|max:100','department'=>'nullable|string|max:100','email'=>'nullable|email|max:150','phone'=>'nullable|string|max:30','joining_date'=>'nullable|date','bank_account'=>'nullable|string|max:50','parent_id'=>'nullable|integer','is_active'=>'boolean']);
        $v['is_active'] = $request->boolean('is_active',true);
        $employee->update($v);
        return redirect()->route('masters.employees.index')->with('success',"Employee '{$employee->name}' updated.");
    }
    public function destroy(Employee $employee) {
        $this->gate('delete'); $this->sc($employee);
        $n=$employee->name; $employee->delete();
        return back()->with('success',"Employee '$n' deleted.");
    }
    public function toggleActive(Employee $employee) {
        $this->gate('edit'); $this->sc($employee);
        $employee->update(['is_active'=>!$employee->is_active]);
        return back()->with('success','Employee status updated.');
    }
    private function gate(string $a='view') { if(!auth()->user()->hasPermission('masters',$a==='view'?'view':($a==='create'?'create':($a==='edit'?'edit':'delete')))) abort(403); }
    private function sc(Employee $e) { if($e->company_id!==auth()->user()->company_id) abort(403); }
}
PHPEOF

echo "=== 5. Writing OtherNamesController ==="
cat > app/Http/Controllers/Company/Masters/OtherNamesController.php << 'PHPEOF'
<?php
namespace App\Http\Controllers\Company\Masters;
use App\Http\Controllers\Controller;
use App\Models\{AuditLog, OtherName};
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
class OtherNamesController extends Controller {
    public function index(Request $request) {
        $this->gate();
        $cid = auth()->user()->company_id;
        $q = OtherName::withoutGlobalScopes()->where('company_id',$cid)->whereNull('deleted_at');
        if ($request->filled('search')) { $s=$request->search; $q->where(fn($x)=>$x->where('name','like',"%$s%")->orWhere('code','like',"%$s%")); }
        if ($request->filled('status')) { $q->where('is_active',$request->status==='active'); }
        $others = $q->orderBy('name')->paginate(25)->withQueryString();
        $stats = ['total'=>OtherName::withoutGlobalScopes()->where('company_id',$cid)->whereNull('deleted_at')->count(),'active'=>OtherName::withoutGlobalScopes()->where('company_id',$cid)->whereNull('deleted_at')->where('is_active',true)->count()];
        return view('masters.other-names.index',compact('others','stats'));
    }
    public function store(Request $request) {
        $this->gate('create');
        $cid = auth()->user()->company_id;
        $v = $request->validate(['code'=>['nullable','string','max:30',Rule::unique('other_names')->where(fn($q)=>$q->where('company_id',$cid)->whereNull('deleted_at'))],'name'=>'required|string|max:150','type'=>'nullable|string|max:50','phone'=>'nullable|string|max:30','email'=>'nullable|email|max:150','address'=>'nullable|string|max:500']);
        $o = OtherName::withoutGlobalScopes()->create(array_merge($v,['company_id'=>$cid,'is_active'=>true]));
        return back()->with('success',"'{$o->name}' added.");
    }
    public function update(Request $request, OtherName $otherName) {
        $this->gate('edit'); $this->sc($otherName);
        $cid = auth()->user()->company_id;
        $v = $request->validate(['code'=>['nullable','string','max:30',Rule::unique('other_names')->where(fn($q)=>$q->where('company_id',$cid)->whereNull('deleted_at'))->ignore($otherName->id)],'name'=>'required|string|max:150','type'=>'nullable|string|max:50','phone'=>'nullable|string|max:30','email'=>'nullable|email|max:150','address'=>'nullable|string|max:500','is_active'=>'boolean']);
        $v['is_active'] = $request->boolean('is_active',true);
        $otherName->update($v);
        return back()->with('success',"'{$otherName->name}' updated.");
    }
    public function destroy(OtherName $otherName) {
        $this->gate('delete'); $this->sc($otherName);
        $n=$otherName->name; $otherName->delete();
        return back()->with('success',"'$n' deleted.");
    }
    private function gate(string $a='view') { if(!auth()->user()->hasPermission('masters',$a==='view'?'view':($a==='create'?'create':($a==='edit'?'edit':'delete')))) abort(403); }
    private function sc(OtherName $o) { if($o->company_id!==auth()->user()->company_id) abort(403); }
}
PHPEOF

echo "=== 6. Creating Employee views ==="
mkdir -p resources/views/masters/employees
mkdir -p resources/views/masters/other-names

cat > resources/views/masters/employees/index.blade.php << 'BLADEEOF'
@extends('layouts.app')
@section('title','Employees')
@section('breadcrumb')
<li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
<li class="breadcrumb-item active">Employees</li>
@endsection
@section('content')
<div class="page-header">
    <div>
        <h1 class="page-title">Employees</h1>
        <p class="page-subtitle">{{ $stats['total'] }} total &nbsp;·&nbsp; <span class="text-success">{{ $stats['active'] }} active</span></p>
    </div>
    @if(auth()->user()->hasPermission('masters','create'))
    <a href="{{ route('masters.employees.create') }}" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>New Employee</a>
    @endif
</div>
@if(session('success'))<div class="alert alert-success alert-dismissible d-flex gap-2 mb-3"><i class="bi bi-check-circle flex-shrink-0"></i><div>{{ session('success') }}</div><button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button></div>@endif
<div class="card mb-3"><div class="card-body py-2 px-3">
<form method="GET"><div class="row g-2 align-items-center">
<div class="col-12 col-sm-5"><input type="text" name="search" class="form-control form-control-sm" placeholder="Search name, code, email…" value="{{ request('search') }}"></div>
<div class="col-6 col-sm-2"><select name="status" class="form-select form-select-sm"><option value="">All Status</option><option value="active" {{ request('status')==='active'?'selected':'' }}>Active</option><option value="inactive" {{ request('status')==='inactive'?'selected':'' }}>Inactive</option></select></div>
<div class="col-3 col-sm-1"><button type="submit" class="btn btn-primary btn-sm w-100"><i class="bi bi-search"></i></button></div>
<div class="col-3 col-sm-1"><a href="{{ route('masters.employees.index') }}" class="btn btn-outline-secondary btn-sm w-100"><i class="bi bi-x-lg"></i></a></div>
</div></form></div></div>
<div class="card"><div class="card-body p-0"><div class="table-responsive">
<table class="table table-hover mb-0" style="min-width:580px">
<thead class="table-light"><tr><th class="ps-4">Name</th><th class="d-none d-md-table-cell">Code</th><th class="d-none d-sm-table-cell">Designation</th><th class="d-none d-md-table-cell">Department</th><th class="d-none d-lg-table-cell">Phone</th><th>Status</th><th class="text-end pe-4">Actions</th></tr></thead>
<tbody>
@forelse($employees as $emp)
<tr>
<td class="ps-4"><div class="fw-semibold" style="font-size:13.5px">{{ $emp->name }}</div><div class="text-muted d-sm-none" style="font-size:12px">{{ $emp->designation }}</div></td>
<td class="d-none d-md-table-cell text-muted" style="font-size:13px">{{ $emp->code ?? '—' }}</td>
<td class="d-none d-sm-table-cell" style="font-size:13px">{{ $emp->designation ?? '—' }}</td>
<td class="d-none d-md-table-cell" style="font-size:13px">{{ $emp->department ?? '—' }}</td>
<td class="d-none d-lg-table-cell" style="font-size:13px">{{ $emp->phone ?? '—' }}</td>
<td><span class="badge" style="font-size:11px;background:{{ $emp->is_active?'#d1e7dd':'#e9ecef' }};color:{{ $emp->is_active?'#0a3622':'#495057' }}">{{ $emp->is_active?'Active':'Inactive' }}</span></td>
<td class="text-end pe-3"><div class="d-flex justify-content-end gap-1">
@if(auth()->user()->hasPermission('masters','edit'))
<a href="{{ route('masters.employees.edit',$emp) }}" class="btn btn-outline-secondary btn-sm" title="Edit"><i class="bi bi-pencil"></i></a>
<form method="POST" action="{{ route('masters.employees.toggle',$emp) }}">@csrf @method('PATCH')<button type="submit" class="btn btn-sm {{ $emp->is_active?'btn-outline-warning':'btn-outline-success' }}" title="{{ $emp->is_active?'Deactivate':'Activate' }}"><i class="bi bi-{{ $emp->is_active?'eye-slash':'eye' }}"></i></button></form>
@endif
@if(auth()->user()->hasPermission('masters','delete'))
<form method="POST" action="{{ route('masters.employees.destroy',$emp) }}" onsubmit="return confirm('Delete {{ addslashes($emp->name) }}?')">@csrf @method('DELETE')<button type="submit" class="btn btn-outline-danger btn-sm"><i class="bi bi-trash"></i></button></form>
@endif
</div></td>
</tr>
@empty
<tr><td colspan="7" class="text-center py-5 text-muted"><i class="bi bi-people display-5 d-block mb-2"></i>No employees found.@if(auth()->user()->hasPermission('masters','create'))<div class="mt-2"><a href="{{ route('masters.employees.create') }}" class="btn btn-primary btn-sm">Add First Employee</a></div>@endif</td></tr>
@endforelse
</tbody></table></div>
@if($employees->hasPages())<div class="px-4 py-3 border-top">{{ $employees->links() }}</div>@endif
</div></div>
@endsection
BLADEEOF

cat > resources/views/masters/employees/create.blade.php << 'BLADEEOF'
@extends('layouts.app')
@section('title', isset($employee) ? 'Edit Employee' : 'New Employee')
@section('breadcrumb')
<li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
<li class="breadcrumb-item"><a href="{{ route('masters.employees.index') }}">Employees</a></li>
<li class="breadcrumb-item active">{{ isset($employee) ? 'Edit' : 'New' }}</li>
@endsection
@section('content')
<div class="page-header">
    <h1 class="page-title">{{ isset($employee) ? 'Edit Employee' : 'New Employee' }}</h1>
    <a href="{{ route('masters.employees.index') }}" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i>Back</a>
</div>
<form method="POST" action="{{ isset($employee) ? route('masters.employees.update',$employee) : route('masters.employees.store') }}">
@csrf
@if(isset($employee)) @method('PUT') @endif
@if($errors->any())<div class="alert alert-danger mb-3">@foreach($errors->all() as $e)<div>{{ $e }}</div>@endforeach</div>@endif
<div class="row g-4">
<div class="col-12 col-xl-8">
<div class="card mb-4">
<div class="card-header fw-semibold"><i class="bi bi-person me-2 text-primary"></i>Employee Details</div>
<div class="card-body"><div class="row g-3">
<div class="col-12"><label class="form-label fw-semibold">Full Name <span class="text-danger">*</span></label><input type="text" name="name" class="form-control @error('name') is-invalid @enderror" value="{{ old('name',$employee->name??'') }}" required autofocus>@error('name')<div class="invalid-feedback">{{ $message }}</div>@enderror</div>
<div class="col-12 col-sm-6"><label class="form-label fw-semibold">Employee Code</label><input type="text" name="code" class="form-control @error('code') is-invalid @enderror" value="{{ old('code',$employee->code??'') }}" placeholder="e.g. EMP001">@error('code')<div class="invalid-feedback">{{ $message }}</div>@enderror</div>
<div class="col-12 col-sm-6"><label class="form-label fw-semibold">Joining Date</label><input type="date" name="joining_date" class="form-control" value="{{ old('joining_date',isset($employee)?$employee->joining_date?->format('Y-m-d'):'') }}"></div>
<div class="col-12 col-sm-6"><label class="form-label fw-semibold">Designation</label><input type="text" name="designation" class="form-control" value="{{ old('designation',$employee->designation??'') }}" placeholder="e.g. Accountant"></div>
<div class="col-12 col-sm-6"><label class="form-label fw-semibold">Department</label><input type="text" name="department" class="form-control" value="{{ old('department',$employee->department??'') }}" placeholder="e.g. Finance"></div>
<div class="col-12 col-sm-6"><label class="form-label fw-semibold">Email</label><input type="email" name="email" class="form-control @error('email') is-invalid @enderror" value="{{ old('email',$employee->email??'') }}">@error('email')<div class="invalid-feedback">{{ $message }}</div>@enderror</div>
<div class="col-12 col-sm-6"><label class="form-label fw-semibold">Phone</label><input type="text" name="phone" class="form-control" value="{{ old('phone',$employee->phone??'') }}"></div>
<div class="col-12 col-sm-6"><label class="form-label fw-semibold">Bank Account</label><input type="text" name="bank_account" class="form-control" value="{{ old('bank_account',$employee->bank_account??'') }}" placeholder="Account number"></div>
<div class="col-12 col-sm-6"><label class="form-label fw-semibold">Reports To (Parent)</label><select name="parent_id" class="form-select"><option value="">— None —</option>@foreach($parents as $p)<option value="{{ $p->id }}" {{ old('parent_id',$employee->parent_id??'')==$p->id?'selected':'' }}>{{ $p->name }}{{ $p->code?' ['.$p->code.']':'' }}</option>@endforeach</select></div>
@if(isset($employee))<div class="col-12"><div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="is_active" value="1" id="isActive" {{ old('is_active',$employee->is_active)?'checked':'' }}><label class="form-check-label fw-semibold" for="isActive">Active</label></div></div>@endif
</div></div></div></div>
<div class="col-12 col-xl-4"><div class="card"><div class="card-body">
<a href="{{ route('masters.employees.index') }}" class="btn btn-outline-secondary w-100 mb-2">Cancel</a>
<button type="submit" class="btn btn-primary w-100"><i class="bi bi-check-circle me-1"></i>{{ isset($employee)?'Save Changes':'Create Employee' }}</button>
</div></div></div>
</div>
</form>
@endsection
BLADEEOF

cp resources/views/masters/employees/create.blade.php resources/views/masters/employees/edit.blade.php

echo "=== 7. Creating Other Names view ==="
cat > resources/views/masters/other-names/index.blade.php << 'BLADEEOF'
@extends('layouts.app')
@section('title','Other Names')
@section('breadcrumb')
<li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
<li class="breadcrumb-item active">Other Names</li>
@endsection
@section('content')
<div class="page-header">
    <div><h1 class="page-title">Other Names</h1><p class="page-subtitle">{{ $stats['total'] }} total &nbsp;·&nbsp; <span class="text-success">{{ $stats['active'] }} active</span></p></div>
    @if(auth()->user()->hasPermission('masters','create'))<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal"><i class="bi bi-plus-lg me-1"></i>New Other Name</button>@endif
</div>
@if(session('success'))<div class="alert alert-success alert-dismissible d-flex gap-2 mb-3"><i class="bi bi-check-circle flex-shrink-0"></i><div>{{ session('success') }}</div><button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button></div>@endif
@if($errors->any())<div class="alert alert-danger alert-dismissible mb-3">@foreach($errors->all() as $e)<div>{{ $e }}</div>@endforeach<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>@endif
<div class="card mb-3"><div class="card-body py-2 px-3"><form method="GET"><div class="row g-2 align-items-center">
<div class="col-12 col-sm-5"><input type="text" name="search" class="form-control form-control-sm" placeholder="Search name or code…" value="{{ request('search') }}"></div>
<div class="col-6 col-sm-2"><select name="status" class="form-select form-select-sm"><option value="">All Status</option><option value="active" {{ request('status')==='active'?'selected':'' }}>Active</option><option value="inactive" {{ request('status')==='inactive'?'selected':'' }}>Inactive</option></select></div>
<div class="col-3 col-sm-1"><button type="submit" class="btn btn-primary btn-sm w-100"><i class="bi bi-search"></i></button></div>
<div class="col-3 col-sm-1"><a href="{{ route('masters.other-names.index') }}" class="btn btn-outline-secondary btn-sm w-100"><i class="bi bi-x-lg"></i></a></div>
</div></form></div></div>
<div class="card"><div class="card-body p-0"><div class="table-responsive">
<table class="table table-hover mb-0" style="min-width:500px">
<thead class="table-light"><tr><th class="ps-4">Name</th><th class="d-none d-sm-table-cell">Code</th><th class="d-none d-md-table-cell">Type</th><th class="d-none d-lg-table-cell">Phone</th><th class="d-none d-lg-table-cell">Email</th><th>Status</th><th class="text-end pe-4">Actions</th></tr></thead>
<tbody>
@forelse($others as $other)
<tr>
<td class="ps-4"><div class="fw-semibold" style="font-size:13.5px">{{ $other->name }}</div></td>
<td class="d-none d-sm-table-cell text-muted" style="font-size:13px">{{ $other->code??'—' }}</td>
<td class="d-none d-md-table-cell" style="font-size:13px">{{ $other->type??'—' }}</td>
<td class="d-none d-lg-table-cell" style="font-size:13px">{{ $other->phone??'—' }}</td>
<td class="d-none d-lg-table-cell" style="font-size:13px">{{ $other->email??'—' }}</td>
<td><span class="badge" style="font-size:11px;background:{{ $other->is_active?'#d1e7dd':'#e9ecef' }};color:{{ $other->is_active?'#0a3622':'#495057' }}">{{ $other->is_active?'Active':'Inactive' }}</span></td>
<td class="text-end pe-3"><div class="d-flex justify-content-end gap-1">
@if(auth()->user()->hasPermission('masters','edit'))<button type="button" class="btn btn-outline-secondary btn-sm btn-edit-other" data-id="{{ $other->id }}" data-name="{{ $other->name }}" data-code="{{ $other->code??'' }}" data-type="{{ $other->type??'' }}" data-phone="{{ $other->phone??'' }}" data-email="{{ $other->email??'' }}" data-address="{{ $other->address??'' }}" data-url="{{ route('masters.other-names.update',$other) }}" title="Edit"><i class="bi bi-pencil"></i></button>@endif
@if(auth()->user()->hasPermission('masters','delete'))<form method="POST" action="{{ route('masters.other-names.destroy',$other) }}" onsubmit="return confirm('Delete?')">@csrf @method('DELETE')<button type="submit" class="btn btn-outline-danger btn-sm"><i class="bi bi-trash"></i></button></form>@endif
</div></td>
</tr>
@empty
<tr><td colspan="7" class="text-center py-5 text-muted"><i class="bi bi-person-lines-fill display-5 d-block mb-2"></i>No other names found.</td></tr>
@endforelse
</tbody></table></div>
@if($others->hasPages())<div class="px-4 py-3 border-top">{{ $others->links() }}</div>@endif
</div></div>
<div class="modal fade" id="addModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
<div class="modal-header border-0 pb-0"><h5 class="modal-title fw-semibold">New Other Name</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
<form method="POST" action="{{ route('masters.other-names.store') }}">@csrf
<div class="modal-body"><div class="row g-3">
<div class="col-12"><label class="form-label fw-semibold">Name <span class="text-danger">*</span></label><input type="text" name="name" class="form-control" required></div>
<div class="col-6"><label class="form-label fw-semibold">Code</label><input type="text" name="code" class="form-control" placeholder="e.g. ON001"></div>
<div class="col-6"><label class="form-label fw-semibold">Type</label><input type="text" name="type" class="form-control" placeholder="e.g. Partner"></div>
<div class="col-6"><label class="form-label fw-semibold">Phone</label><input type="text" name="phone" class="form-control"></div>
<div class="col-6"><label class="form-label fw-semibold">Email</label><input type="email" name="email" class="form-control"></div>
<div class="col-12"><label class="form-label fw-semibold">Address</label><textarea name="address" class="form-control" rows="2"></textarea></div>
</div></div>
<div class="modal-footer border-0 pt-0"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary px-4"><i class="bi bi-check-circle me-1"></i>Save</button></div>
</form></div></div></div>
<div class="modal fade" id="editModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
<div class="modal-header border-0 pb-0"><h5 class="modal-title fw-semibold">Edit Other Name</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
<form method="POST" id="editForm">@csrf @method('PUT')
<div class="modal-body"><div class="row g-3">
<div class="col-12"><label class="form-label fw-semibold">Name <span class="text-danger">*</span></label><input type="text" name="name" id="editName" class="form-control" required></div>
<div class="col-6"><label class="form-label fw-semibold">Code</label><input type="text" name="code" id="editCode" class="form-control"></div>
<div class="col-6"><label class="form-label fw-semibold">Type</label><input type="text" name="type" id="editType" class="form-control"></div>
<div class="col-6"><label class="form-label fw-semibold">Phone</label><input type="text" name="phone" id="editPhone" class="form-control"></div>
<div class="col-6"><label class="form-label fw-semibold">Email</label><input type="email" name="email" id="editEmail" class="form-control"></div>
<div class="col-12"><label class="form-label fw-semibold">Address</label><textarea name="address" id="editAddress" class="form-control" rows="2"></textarea></div>
</div></div>
<div class="modal-footer border-0 pt-0"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary px-4"><i class="bi bi-check-circle me-1"></i>Save</button></div>
</form></div></div></div>
@endsection
@push('scripts')
<script>
document.querySelectorAll('.btn-edit-other').forEach(function(btn){
    btn.addEventListener('click',function(){
        document.getElementById('editForm').action=this.dataset.url;
        document.getElementById('editName').value=this.dataset.name;
        document.getElementById('editCode').value=this.dataset.code;
        document.getElementById('editType').value=this.dataset.type;
        document.getElementById('editPhone').value=this.dataset.phone;
        document.getElementById('editEmail').value=this.dataset.email;
        document.getElementById('editAddress').value=this.dataset.address;
        new bootstrap.Modal(document.getElementById('editModal')).show();
    });
});
</script>
@endpush
BLADEEOF

echo "=== 8. Updating Item Model with parent_id ==="
grep -q "'parent_id'" app/Models/Item.php || sed -i "s/'company_id','category_id'/'company_id','parent_id','category_id'/" app/Models/Item.php

echo "=== 9. Adding parent item to Items create view ==="
grep -q "Parent Item" resources/views/inventory/items/create.blade.php || python3 << 'PYEOF'
content = open('resources/views/inventory/items/create.blade.php').read()
old = '                            <div class="col-12">\n                                <label class="form-label fw-semibold">Description</label>'
new = '''                            <div class="col-12 col-sm-6">
                                <label class="form-label fw-semibold">Parent Item</label>
                                <select name="parent_id" class="form-select select2">
                                    <option value="">&#8212; No Parent (Top Level) &#8212;</option>
                                    @foreach(\\App\\Models\\Item::withoutGlobalScopes()->where('company_id',auth()->user()->company_id)->whereNull('deleted_at')->where('is_active',true)->orderBy('name')->get(['id','code','name']) as $pi)
                                        <option value="{{ $pi->id }}" {{ old('parent_id',$item->parent_id??'')==$pi->id?'selected':'' }}>
                                            {{ $pi->code?'['.$pi->code.'] ':'' }}{{ $pi->name }}
                                        </option>
                                    @endforeach
                                </select>
                                <div class="form-text">Optional &#8212; group this under a parent item</div>
                            </div>

                            <div class="col-12 col-sm-6">
                                <label class="form-label fw-semibold">Description</label>'''
content = content.replace(old, new, 1)
open('resources/views/inventory/items/create.blade.php','w').write(content)
import shutil
shutil.copy('resources/views/inventory/items/create.blade.php','resources/views/inventory/items/edit.blade.php')
print("Items views updated")
PYEOF

echo "=== 10. Updating Routes ==="
cat > routes/web.php << 'ROUTESEOF'
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SuperAdmin\{AuthController as SAAuthController, DashboardController as SADashController};
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Company\DashboardController;
use App\Http\Controllers\Company\Settings\CompanySettingsController;
use App\Http\Controllers\Company\Admin\{UsersController, RolesController, FiscalYearsController, VoucherNumberingController, AuditTrailController};
use App\Http\Controllers\Company\Accounting\{ChartOfAccountsController, DimensionsController};
use App\Http\Controllers\Company\Masters\{CustomersController, VendorsController, CurrenciesController, TaxCodesController, PriceLevelsController, EmployeesController, OtherNamesController};
use App\Http\Controllers\Company\Inventory\{ItemsController, UomsController, ItemCategoriesController, WarehousesController};
use App\Http\Controllers\Company\Accounting\AccountingVouchersController;

$saPrefix = env('SUPER_ADMIN_PREFIX', 'sadmin');

Route::prefix($saPrefix)->name('sadmin.')->group(function () {
    Route::get('/login',  [SAAuthController::class, 'showLogin'])->name('login');
    Route::post('/login', [SAAuthController::class, 'login'])->name('login.post');
    Route::middleware('auth:super_admin')->group(function () {
        Route::post('/logout',                      [SAAuthController::class, 'logout'])->name('logout');
        Route::get('/',                             [SADashController::class, 'dashboard'])->name('dashboard');
        Route::get('/dashboard',                    [SADashController::class, 'dashboard']);
        Route::get('/companies',                    [SADashController::class, 'companies'])->name('companies');
        Route::get('/companies/create',             [SADashController::class, 'createCompany'])->name('companies.create');
        Route::post('/companies',                   [SADashController::class, 'storeCompany'])->name('companies.store');
        Route::get('/companies/{company}/edit',     [SADashController::class, 'editCompany'])->name('companies.edit');
        Route::put('/companies/{company}',          [SADashController::class, 'updateCompany'])->name('companies.update');
        Route::patch('/companies/{company}/toggle', [SADashController::class, 'toggleStatus'])->name('companies.toggle');
        Route::get('/online-users',                 [SADashController::class, 'onlineUsers'])->name('online-users');
        Route::post('/force-logout',                [SADashController::class, 'forceLogout'])->name('force-logout');
        Route::get('/audit-logs',                   [SADashController::class, 'auditLogs'])->name('audit-logs');
    });
});

Route::get('/login',  [LoginController::class, 'showLogin'])->name('login');
Route::post('/login', [LoginController::class, 'login'])->name('login.post');

Route::middleware(['auth:web','company.active','concurrent.users','password.changed'])->group(function () {

    Route::post('/logout',          [LoginController::class, 'logout'])->name('logout');
    Route::get('/password/change',  [LoginController::class, 'showChangePassword'])->name('password.change');
    Route::post('/password/change', [LoginController::class, 'changePassword'])->name('password.update');
    Route::get('/',          [DashboardController::class, 'index'])->name('dashboard');
    Route::get('/dashboard', [DashboardController::class, 'index']);

    Route::prefix('settings')->name('settings.')->group(function () {
        Route::get('/general',    [CompanySettingsController::class, 'general'])->name('general');
        Route::put('/general',    [CompanySettingsController::class, 'updateGeneral'])->name('general.update');
        Route::get('/accounting', [CompanySettingsController::class, 'accounting'])->name('accounting');
        Route::put('/accounting', [CompanySettingsController::class, 'updateAccounting'])->name('accounting.update');
        Route::get('/security',   [CompanySettingsController::class, 'security'])->name('security');
        Route::put('/security',   [CompanySettingsController::class, 'updateSecurity'])->name('security.update');
    });

    Route::prefix('admin')->name('admin.')->group(function () {
        Route::prefix('users')->name('users.')->group(function () {
            Route::get('/',                       [UsersController::class, 'index'])->name('index');
            Route::get('/create',                 [UsersController::class, 'create'])->name('create');
            Route::post('/',                      [UsersController::class, 'store'])->name('store');
            Route::get('/{user}/edit',            [UsersController::class, 'edit'])->name('edit');
            Route::put('/{user}',                 [UsersController::class, 'update'])->name('update');
            Route::post('/{user}/reset-password', [UsersController::class, 'resetPassword'])->name('reset-password');
            Route::patch('/{user}/toggle-active', [UsersController::class, 'toggleActive'])->name('toggle-active');
            Route::delete('/{user}',              [UsersController::class, 'destroy'])->name('destroy');
        });
        Route::prefix('roles')->name('roles.')->group(function () {
            Route::get('/',             [RolesController::class, 'index'])->name('index');
            Route::get('/create',       [RolesController::class, 'create'])->name('create');
            Route::post('/',            [RolesController::class, 'store'])->name('store');
            Route::get('/{role}/edit',  [RolesController::class, 'edit'])->name('edit');
            Route::put('/{role}',       [RolesController::class, 'update'])->name('update');
            Route::delete('/{role}',    [RolesController::class, 'destroy'])->name('destroy');
        });
        Route::prefix('fiscal-years')->name('fiscal-years.')->group(function () {
            Route::get('/',                           [FiscalYearsController::class, 'index'])->name('index');
            Route::get('/create',                     [FiscalYearsController::class, 'create'])->name('create');
            Route::post('/',                          [FiscalYearsController::class, 'store'])->name('store');
            Route::patch('/{fiscalYear}/set-current', [FiscalYearsController::class, 'setCurrent'])->name('set-current');
            Route::patch('/{fiscalYear}/lock',        [FiscalYearsController::class, 'lock'])->name('lock');
        });
        Route::prefix('voucher-numbering')->name('voucher-numbering.')->group(function () {
            Route::get('/',                   [VoucherNumberingController::class, 'index'])->name('index');
            Route::get('/{voucherType}/edit', [VoucherNumberingController::class, 'edit'])->name('edit');
            Route::put('/{voucherType}',      [VoucherNumberingController::class, 'update'])->name('update');
            Route::post('/preview',           [VoucherNumberingController::class, 'previewAjax'])->name('preview');
        });
        Route::get('/audit-trail', [AuditTrailController::class, 'index'])->name('audit-trail');
    });

    Route::prefix('accounting')->name('coa.')->group(function () {
        Route::get('/accounts/search',         [ChartOfAccountsController::class, 'search'])->name('search');
        Route::get('/accounts',                [ChartOfAccountsController::class, 'index'])->name('index');
        Route::get('/accounts/create',         [ChartOfAccountsController::class, 'create'])->name('create');
        Route::post('/accounts',               [ChartOfAccountsController::class, 'store'])->name('store');
        Route::get('/accounts/{account}/edit', [ChartOfAccountsController::class, 'edit'])->name('edit');
        Route::put('/accounts/{account}',      [ChartOfAccountsController::class, 'update'])->name('update');
        Route::delete('/accounts/{account}',   [ChartOfAccountsController::class, 'destroy'])->name('destroy');
    });

    Route::prefix('accounting/dimensions')->name('dimensions.')->group(function () {
        Route::get('/',                              [DimensionsController::class, 'index'])->name('index');
        Route::put('/slots',                         [DimensionsController::class, 'updateSlots'])->name('update-slots');
        Route::get('/search/{slot}',                 [DimensionsController::class, 'searchValues'])->name('search');
        Route::get('/{dimension}/values',            [DimensionsController::class, 'values'])->name('values');
        Route::post('/{dimension}/values',           [DimensionsController::class, 'storeValue'])->name('values.store');
        Route::put('/{dimension}/values/{value}',    [DimensionsController::class, 'updateValue'])->name('values.update');
        Route::delete('/{dimension}/values/{value}', [DimensionsController::class, 'destroyValue'])->name('values.destroy');
    });

    Route::prefix('masters')->name('masters.')->group(function () {
        Route::prefix('customers')->name('customers.')->group(function () {
            Route::get('/search',              [CustomersController::class, 'search'])->name('search');
            Route::get('/',                    [CustomersController::class, 'index'])->name('index');
            Route::get('/create',              [CustomersController::class, 'create'])->name('create');
            Route::post('/',                   [CustomersController::class, 'store'])->name('store');
            Route::get('/{customer}/edit',     [CustomersController::class, 'edit'])->name('edit');
            Route::put('/{customer}',          [CustomersController::class, 'update'])->name('update');
            Route::patch('/{customer}/toggle', [CustomersController::class, 'toggleActive'])->name('toggle');
            Route::delete('/{customer}',       [CustomersController::class, 'destroy'])->name('destroy');
        });
        Route::prefix('vendors')->name('vendors.')->group(function () {
            Route::get('/search',            [VendorsController::class, 'search'])->name('search');
            Route::get('/',                  [VendorsController::class, 'index'])->name('index');
            Route::get('/create',            [VendorsController::class, 'create'])->name('create');
            Route::post('/',                 [VendorsController::class, 'store'])->name('store');
            Route::get('/{vendor}/edit',     [VendorsController::class, 'edit'])->name('edit');
            Route::put('/{vendor}',          [VendorsController::class, 'update'])->name('update');
            Route::patch('/{vendor}/toggle', [VendorsController::class, 'toggleActive'])->name('toggle');
            Route::delete('/{vendor}',       [VendorsController::class, 'destroy'])->name('destroy');
        });
        Route::prefix('currencies')->name('currencies.')->group(function () {
            Route::get('/',                [CurrenciesController::class, 'index'])->name('index');
            Route::post('/',               [CurrenciesController::class, 'store'])->name('store');
            Route::put('/{currency}',      [CurrenciesController::class, 'update'])->name('update');
            Route::put('/{currency}/rate', [CurrenciesController::class, 'updateRate'])->name('rate');
        });
        Route::prefix('tax-codes')->name('tax-codes.')->group(function () {
            Route::get('/search',       [TaxCodesController::class, 'search'])->name('search');
            Route::get('/',             [TaxCodesController::class, 'index'])->name('index');
            Route::post('/',            [TaxCodesController::class, 'store'])->name('store');
            Route::put('/{taxCode}',    [TaxCodesController::class, 'update'])->name('update');
            Route::delete('/{taxCode}', [TaxCodesController::class, 'destroy'])->name('destroy');
        });
        Route::prefix('price-levels')->name('price-levels.')->group(function () {
            Route::get('/',                [PriceLevelsController::class, 'index'])->name('index');
            Route::post('/',               [PriceLevelsController::class, 'store'])->name('store');
            Route::put('/{priceLevel}',    [PriceLevelsController::class, 'update'])->name('update');
            Route::delete('/{priceLevel}', [PriceLevelsController::class, 'destroy'])->name('destroy');
        });
        Route::prefix('employees')->name('employees.')->group(function () {
            Route::get('/',                    [EmployeesController::class, 'index'])->name('index');
            Route::get('/create',              [EmployeesController::class, 'create'])->name('create');
            Route::post('/',                   [EmployeesController::class, 'store'])->name('store');
            Route::get('/{employee}/edit',     [EmployeesController::class, 'edit'])->name('edit');
            Route::put('/{employee}',          [EmployeesController::class, 'update'])->name('update');
            Route::patch('/{employee}/toggle', [EmployeesController::class, 'toggleActive'])->name('toggle');
            Route::delete('/{employee}',       [EmployeesController::class, 'destroy'])->name('destroy');
        });
        Route::prefix('other-names')->name('other-names.')->group(function () {
            Route::get('/',                [OtherNamesController::class, 'index'])->name('index');
            Route::post('/',               [OtherNamesController::class, 'store'])->name('store');
            Route::put('/{otherName}',     [OtherNamesController::class, 'update'])->name('update');
            Route::delete('/{otherName}',  [OtherNamesController::class, 'destroy'])->name('destroy');
        });
    });

    Route::prefix('inventory')->name('inventory.')->group(function () {
        Route::prefix('items')->name('items.')->group(function () {
            Route::get('/search',          [ItemsController::class, 'search'])->name('search');
            Route::get('/',                [ItemsController::class, 'index'])->name('index');
            Route::get('/create',          [ItemsController::class, 'create'])->name('create');
            Route::post('/',               [ItemsController::class, 'store'])->name('store');
            Route::get('/{item}/edit',     [ItemsController::class, 'edit'])->name('edit');
            Route::put('/{item}',          [ItemsController::class, 'update'])->name('update');
            Route::patch('/{item}/toggle', [ItemsController::class, 'toggleActive'])->name('toggle');
            Route::delete('/{item}',       [ItemsController::class, 'destroy'])->name('destroy');
        });
        Route::prefix('uoms')->name('uoms.')->group(function () {
            Route::get('/',          [UomsController::class, 'index'])->name('index');
            Route::post('/',         [UomsController::class, 'store'])->name('store');
            Route::put('/{uom}',     [UomsController::class, 'update'])->name('update');
            Route::delete('/{uom}',  [UomsController::class, 'destroy'])->name('destroy');
        });
        Route::prefix('categories')->name('categories.')->group(function () {
            Route::get('/',                  [ItemCategoriesController::class, 'index'])->name('index');
            Route::post('/',                 [ItemCategoriesController::class, 'store'])->name('store');
            Route::put('/{itemCategory}',    [ItemCategoriesController::class, 'update'])->name('update');
            Route::delete('/{itemCategory}', [ItemCategoriesController::class, 'destroy'])->name('destroy');
        });
        Route::prefix('warehouses')->name('warehouses.')->group(function () {
            Route::get('/search',          [WarehousesController::class, 'search'])->name('search');
            Route::get('/',                [WarehousesController::class, 'index'])->name('index');
            Route::post('/',               [WarehousesController::class, 'store'])->name('store');
            Route::put('/{warehouse}',     [WarehousesController::class, 'update'])->name('update');
            Route::delete('/{warehouse}',  [WarehousesController::class, 'destroy'])->name('destroy');
        });
    });

    Route::prefix('accounting')->group(function () {
        Route::get('/vouchers/{voucherType}',        [AccountingVouchersController::class, 'index'])->name('vouchers.index');
        Route::get('/vouchers/{voucherType}/create', [AccountingVouchersController::class, 'create'])->name('vouchers.create');
        Route::post('/vouchers/{voucherType}',       [AccountingVouchersController::class, 'store'])->name('vouchers.store');
        Route::get('/vouchers/{voucherType}/{voucher}',       [AccountingVouchersController::class, 'show'])->name('vouchers.show');
        Route::get('/vouchers/{voucherType}/{voucher}/edit',  [AccountingVouchersController::class, 'edit'])->name('vouchers.edit');
        Route::put('/vouchers/{voucherType}/{voucher}',       [AccountingVouchersController::class, 'update'])->name('vouchers.update');
        Route::delete('/vouchers/{voucherType}/{voucher}',    [AccountingVouchersController::class, 'destroy'])->name('vouchers.destroy');
        Route::post('/vouchers/{voucherType}/{voucher}/submit',  [AccountingVouchersController::class, 'submit'])->name('vouchers.submit');
        Route::post('/vouchers/{voucherType}/{voucher}/approve', [AccountingVouchersController::class, 'approve'])->name('vouchers.approve');
        Route::post('/vouchers/{voucherType}/{voucher}/reject',  [AccountingVouchersController::class, 'reject'])->name('vouchers.reject');
        Route::post('/vouchers/{voucherType}/{voucher}/post',    [AccountingVouchersController::class, 'post'])->name('vouchers.post');
        Route::post('/vouchers/{voucherType}/{voucher}/cancel',  [AccountingVouchersController::class, 'cancel'])->name('vouchers.cancel');
        Route::post('/vouchers/{voucherType}/{voucher}/reverse', [AccountingVouchersController::class, 'reverse'])->name('vouchers.reverse');
    });
});
ROUTESEOF

echo "=== 11. Updating Sidebar ==="
python3 << 'PYEOF'
content = open('resources/views/layouts/app.blade.php').read()

# Add Customers to AR
content = content.replace(
    '        <div class="collapse nav-submenu" id="navAR">\n            <a href="#" class="nav-item-link"><span>Quotations</span></a>',
    '        <div class="collapse nav-submenu" id="navAR">\n            <a href="{{ route(\'masters.customers.index\') }}" class="nav-item-link {{ request()->routeIs(\'masters.customers.*\') ? \'active\':\'\' }}"><span>Customers</span></a>\n            <a href="#" class="nav-item-link"><span>Quotations</span></a>'
)

# Add Vendors to AP
content = content.replace(
    '        <div class="collapse nav-submenu" id="navAP">\n            <a href="#" class="nav-item-link"><span>Purchase Requisitions</span></a>',
    '        <div class="collapse nav-submenu" id="navAP">\n            <a href="{{ route(\'masters.vendors.index\') }}" class="nav-item-link {{ request()->routeIs(\'masters.vendors.*\') ? \'active\':\'\' }}"><span>Vendors</span></a>\n            <a href="#" class="nav-item-link"><span>Purchase Requisitions</span></a>'
)

# Add Employees and Other Names, remove Customers/Vendors from Masters
old = '            <a href="{{ route(\'masters.customers.index\') }}"\n               class="nav-item-link {{ request()->routeIs(\'masters.customers.*\') ? \'active\':\'\' }}">\n                <span>Customers</span>\n            </a>\n            <a href="{{ route(\'masters.vendors.index\') }}"\n               class="nav-item-link {{ request()->routeIs(\'masters.vendors.*\') ? \'active\':\'\' }}">\n                <span>Vendors</span>\n            </a>\n            <a href="{{ route(\'masters.currencies.index\') }}"'
new = '            <a href="{{ route(\'masters.employees.index\') }}" class="nav-item-link {{ request()->routeIs(\'masters.employees.*\') ? \'active\':\'\' }}"><span>Employees</span></a>\n            <a href="{{ route(\'masters.other-names.index\') }}" class="nav-item-link {{ request()->routeIs(\'masters.other-names.*\') ? \'active\':\'\' }}"><span>Other Names</span></a>\n            <a href="{{ route(\'masters.currencies.index\') }}"'

if old in content:
    content = content.replace(old, new)
    print("Masters menu updated")
else:
    print("Masters menu pattern not found - manual update needed")

open('resources/views/layouts/app.blade.php','w').write(content)
PYEOF

echo "=== 12. Clear & Optimize ==="
php artisan view:clear
php artisan optimize

echo ""
echo "======================================"
echo "  DEPLOY COMPLETE!"
echo "======================================"
echo "  New features:"
echo "  1. Customers -> AR Flow menu"
echo "  2. Vendors   -> AP Flow menu"
echo "  3. Employees -> Master Data menu"
echo "  4. Other Names -> Master Data menu"
echo "  5. Parent Item selector in Items form"
echo "======================================"
