<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\Department;
use App\Models\Employee;
use App\Models\EmployeeSchedule;
use App\Models\Position;
use App\Models\Shift;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;

class EmployeeController extends Controller
{
    public function index(Request $request)
    {
        $query = Employee::with(['department', 'position', 'user', 'schedules.shift']);

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('nik', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        if ($request->filled('department_id')) {
            $query->where('department_id', $request->department_id);
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $employees = $query->latest()->paginate(10)->withQueryString();
        $departments = Department::all();
        $positions = Position::all();
        $shifts = Shift::where('is_active', true)->get();

        $totalActive = Employee::where('status', 'active')->count();
        $totalInactive = Employee::where('status', 'inactive')->count();

        return view('admin.employees.index', compact(
            'employees',
            'departments',
            'positions',
            'shifts',
            'totalActive',
            'totalInactive'
        ));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'nik' => ['required', 'string', 'max:50', 'unique:employees,nik'],
            'email' => ['required', 'email', 'unique:users,email', 'unique:employees,email'],
            'password' => ['nullable', 'string', 'min:6'],
            'phone' => ['nullable', 'string', 'max:20'],
            'gender' => ['required', 'in:male,female'],
            'birth_place' => ['nullable', 'string', 'max:100'],
            'birth_date' => ['nullable', 'date'],
            'address' => ['nullable', 'string'],
            'department_id' => ['nullable', 'exists:departments,id'],
            'position_id' => ['nullable', 'exists:positions,id'],
            'shift_id' => ['nullable', 'exists:shifts,id'],
            'join_date' => ['nullable', 'date'],
            'employment_status' => ['required', 'string', 'in:permanent,contract,internship'],
            'leave_balance' => ['nullable', 'integer', 'min:0'],
            'status' => ['required', 'in:active,inactive'],
            'photo' => ['nullable', 'image', 'mimes:jpeg,png,jpg', 'max:2048'],
        ]);

        DB::transaction(function () use ($request, $validated) {
            $photoPath = null;
            if ($request->hasFile('photo')) {
                $photoPath = $request->file('photo')->store('employees/photos', 'public');
            }

            // Create User
            $user = User::create([
                'name' => $validated['name'],
                'email' => $validated['email'],
                'password' => Hash::make($validated['password'] ?? 'password'),
                'role' => 'employee',
                'status' => $validated['status'],
                'avatar' => $photoPath ? 'storage/' . $photoPath : null,
            ]);

            // Create Employee
            $employee = Employee::create([
                'user_id' => $user->id,
                'nik' => $validated['nik'],
                'name' => $validated['name'],
                'email' => $validated['email'],
                'phone' => $validated['phone'] ?? null,
                'gender' => $validated['gender'],
                'birth_place' => $validated['birth_place'] ?? null,
                'birth_date' => $validated['birth_date'] ?? null,
                'address' => $validated['address'] ?? null,
                'department_id' => $validated['department_id'] ?? null,
                'position_id' => $validated['position_id'] ?? null,
                'join_date' => $validated['join_date'] ?? now()->toDateString(),
                'employment_status' => $validated['employment_status'],
                'photo' => $photoPath ? 'storage/' . $photoPath : null,
                'status' => $validated['status'],
                'leave_balance' => $validated['leave_balance'] ?? 12,
            ]);

            // Assign Shift Schedule
            if (!empty($validated['shift_id'])) {
                EmployeeSchedule::create([
                    'employee_id' => $employee->id,
                    'shift_id' => $validated['shift_id'],
                    'effective_from' => now()->toDateString(),
                    'is_active' => true,
                ]);
            }

            AuditLog::log('Tambah Karyawan', "Menambahkan karyawan baru {$employee->name} ({$employee->nik})");
        });

        return redirect()->route('admin.employees.index')->with('success', 'Data karyawan berhasil ditambahkan.');
    }

    public function update(Request $request, Employee $employee)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'nik' => ['required', 'string', 'max:50', Rule::unique('employees')->ignore($employee->id)],
            'email' => ['required', 'email', Rule::unique('users', 'email')->ignore($employee->user_id), Rule::unique('employees', 'email')->ignore($employee->id)],
            'password' => ['nullable', 'string', 'min:6'],
            'phone' => ['nullable', 'string', 'max:20'],
            'gender' => ['required', 'in:male,female'],
            'birth_place' => ['nullable', 'string', 'max:100'],
            'birth_date' => ['nullable', 'date'],
            'address' => ['nullable', 'string'],
            'department_id' => ['nullable', 'exists:departments,id'],
            'position_id' => ['nullable', 'exists:positions,id'],
            'shift_id' => ['nullable', 'exists:shifts,id'],
            'join_date' => ['nullable', 'date'],
            'employment_status' => ['required', 'string', 'in:permanent,contract,internship'],
            'leave_balance' => ['nullable', 'integer', 'min:0'],
            'status' => ['required', 'in:active,inactive'],
            'photo' => ['nullable', 'image', 'mimes:jpeg,png,jpg', 'max:2048'],
        ]);

        DB::transaction(function () use ($request, $employee, $validated) {
            $photoPath = $employee->photo;
            if ($request->hasFile('photo')) {
                $stored = $request->file('photo')->store('employees/photos', 'public');
                $photoPath = 'storage/' . $stored;
            }

            // Update Employee
            $employee->update([
                'nik' => $validated['nik'],
                'name' => $validated['name'],
                'email' => $validated['email'],
                'phone' => $validated['phone'] ?? $employee->phone,
                'gender' => $validated['gender'],
                'birth_place' => $validated['birth_place'] ?? $employee->birth_place,
                'birth_date' => $validated['birth_date'] ?? $employee->birth_date,
                'address' => $validated['address'] ?? $employee->address,
                'department_id' => $validated['department_id'] ?? $employee->department_id,
                'position_id' => $validated['position_id'] ?? $employee->position_id,
                'join_date' => $validated['join_date'] ?? $employee->join_date,
                'employment_status' => $validated['employment_status'],
                'photo' => $photoPath,
                'status' => $validated['status'],
                'leave_balance' => $validated['leave_balance'] ?? $employee->leave_balance,
            ]);

            // Update User
            if ($employee->user) {
                $userData = [
                    'name' => $validated['name'],
                    'email' => $validated['email'],
                    'status' => $validated['status'],
                    'avatar' => $photoPath,
                ];
                if (!empty($validated['password'])) {
                    $userData['password'] = Hash::make($validated['password']);
                }
                $employee->user->update($userData);
            }

            // Update Shift Schedule
            if (!empty($validated['shift_id'])) {
                EmployeeSchedule::updateOrCreate(
                    [
                        'employee_id' => $employee->id,
                        'is_active' => true,
                    ],
                    [
                        'shift_id' => $validated['shift_id'],
                        'effective_from' => now()->toDateString(),
                    ]
                );
            }

            AuditLog::log('Edit Karyawan', "Memperbarui data karyawan {$employee->name} ({$employee->nik})");
        });

        return redirect()->route('admin.employees.index')->with('success', 'Data karyawan berhasil diperbarui.');
    }

    public function destroy(Employee $employee)
    {
        $name = $employee->name;
        $nik = $employee->nik;

        DB::transaction(function () use ($employee) {
            if ($employee->user) {
                $employee->user->delete();
            } else {
                $employee->delete();
            }
        });

        AuditLog::log('Hapus Karyawan', "Menghapus karyawan {$name} ({$nik})");

        return redirect()->route('admin.employees.index')->with('success', 'Data karyawan berhasil dihapus.');
    }

    public function export(Request $request)
    {
        $employees = Employee::with(['department', 'position'])->orderBy('name')->get();
        $filename = 'Data_Karyawan_' . date('Ymd_His') . '.xls';
        $companyName = \App\Models\AttendanceSetting::get('company_name', config('app.name', 'PT Inovasi Digital Nusantara'));

        $output = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">';
        $output .= '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
        $output .= '<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>Data Karyawan</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->';
        $output .= '<style>
            table { border-collapse: collapse; width: 100%; font-family: "Segoe UI", Arial, sans-serif; font-size: 11pt; }
            th { background-color: #1e293b; color: #ffffff; font-weight: bold; border: 1px solid #cbd5e1; padding: 10px; text-align: center; }
            td { border: 1px solid #cbd5e1; padding: 8px 10px; vertical-align: middle; }
            .header-title { font-size: 16pt; font-weight: bold; color: #0f172a; }
            .header-subtitle { font-size: 12pt; color: #475569; }
            .header-meta { font-size: 9pt; color: #64748b; font-style: italic; }
            .text-center { text-align: center; }
            .text-left { text-align: left; }
            .text-right { text-align: right; }
        </style>';
        $output .= '</head><body>';

        $output .= '<table>';
        $output .= '<tr><td colspan="11" class="header-title">' . htmlspecialchars($companyName) . '</td></tr>';
        $output .= '<tr><td colspan="11" class="header-subtitle">DATABASE MASTER KARYAWAN</td></tr>';
        $output .= '<tr><td colspan="11" class="header-meta">Dicetak pada: ' . now()->translatedFormat('d F Y H:i') . ' WIB | Total: ' . count($employees) . ' Karyawan</td></tr>';
        $output .= '<tr><td colspan="11"></td></tr>';

        $output .= '<tr>
            <th>No</th>
            <th>NIK</th>
            <th>Nama Lengkap</th>
            <th>Email</th>
            <th>No. WhatsApp</th>
            <th>Jenis Kelamin</th>
            <th>Departemen</th>
            <th>Jabatan</th>
            <th>Status Kepegawaian</th>
            <th>Tanggal Bergabung</th>
            <th>Sisa Cuti</th>
        </tr>';

        $no = 1;
        foreach ($employees as $emp) {
            $output .= '<tr>
                <td class="text-center">' . $no++ . '</td>
                <td class="text-center" style="mso-number-format:\'@\';">' . htmlspecialchars($emp->nik) . '</td>
                <td class="text-left">' . htmlspecialchars($emp->name) . '</td>
                <td class="text-left">' . htmlspecialchars($emp->email) . '</td>
                <td class="text-center" style="mso-number-format:\'@\';">' . htmlspecialchars($emp->phone ?? '-') . '</td>
                <td class="text-center">' . ($emp->gender === 'male' ? 'Laki-laki' : 'Perempuan') . '</td>
                <td class="text-left">' . htmlspecialchars($emp->department?->name ?? '-') . '</td>
                <td class="text-left">' . htmlspecialchars($emp->position?->name ?? '-') . '</td>
                <td class="text-center">' . ucfirst($emp->employment_status) . '</td>
                <td class="text-center">' . ($emp->join_date ? $emp->join_date->format('d/m/Y') : '-') . '</td>
                <td class="text-center">' . $emp->leave_balance . ' Hari</td>
            </tr>';
        }

        $output .= '</table></body></html>';

        return response($output, 200, [
            'Content-Type' => 'application/vnd.ms-excel; charset=utf-8',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
            'Pragma' => 'no-cache',
            'Expires' => '0',
        ]);
    }
}
