<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Skill;
use App\Exports\SkillExport;
use Maatwebsite\Excel\Facades\Excel;
/*COMPACT_MODAL*/

use DataTables;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

/**
 * Controller for managing Skill resources.
 * 
 * This controller handles CRUD operations including:
 * - Listing, creating, updating, and deleting records
 * - Soft delete and restore functionality
 * - Excel/CSV export functionality
 * - Search and sorting capabilities
 * 
 * @package App\Http\Controllers
 */
class SkillController extends Controller {

    /**
     * Constructor - Set up middleware for permissions
     */
    public function __construct()
    {
        $this->middleware('permission:skills-list')->only(['index', 'show']);
        $this->middleware('permission:skills-create')->only(['create', 'store']);
        $this->middleware('permission:skills-edit')->only(['edit', 'update']);
        $this->middleware('permission:skills-delete')->only(['destroy']);
    }

    /**
     * Store a newly created resource in storage.
     * 
     * Validates the request data and creates a new record in the database.
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
/*1- validate and insert into to database*/
public function store(Request $request) {

$dbs_skills = view()->shared('dbs_skills');

$validator = \Validator::make($request->all(), [
           'name'=>$dbs_skills["name_validateas"].$dbs_skills["name_unique"],

           'description'=>$dbs_skills["description_validateas"].$dbs_skills["description_unique"],

           'status'=>$dbs_skills["status_validateas"].$dbs_skills["status_unique"],


]);


if ($validator->passes()) {
$table = new Skill();



            $table->name = $request->input('name');
            $table->description = $request->input('description');
            $table->status = $request->input('status');

$table->save();
$max_id = $table->id;

/*CHECKBOXQUERY*/


return response()->json(['success' => 'Record has been created successfully.']);
}
return response()->json(['error' => $validator->errors()]);
}

    /**
     * Display a listing of the resource.
     * 
     * Shows paginated list of records with search and sorting functionality.
     * 
     * @param Request $request
     * @return \Illuminate\Contracts\View\View
     */
/*2- view index page*/
public function index(Request $request) {
    $query = Skill::whereNull('deleted_at');
    
    
    
    // Search functionality
    if ($request->has('search') && $request->search != '') {
        $search = $request->search;
        $query->where(function($q) use ($search) {
            $q->orWhere('name', 'like', '%' . $search . '%');
            $q->orWhere('status', 'like', '%' . $search . '%');
        });
    }
    
    // Ordering
    $sortBy = $request->get('sort_by', 'name');
    $sortOrder = $request->get('sort_order', 'asc');
    
    // Validate sort_by to prevent SQL injection
    $allowedSorts = ['id', 'name', 'status'];
    if (!in_array($sortBy, $allowedSorts)) {
        $sortBy = 'name';
    }
    
    // Validate sort_order
    $sortOrder = strtolower($sortOrder) === 'desc' ? 'desc' : 'asc';
    
    $query->orderBy($sortBy, $sortOrder);
    
    // Pagination
    $skills = $query->paginate(10)->withQueryString();
    
    return view('skills.index', compact('skills'));
}

    /**
     * Display the specified resource.
     * 
     * Redirects to the edit page for the specified resource.
     * 
     * @param int $id
     * @return \Illuminate\Http\RedirectResponse
     */
public function show($id) {
    return redirect()->route('skills.edit', $id);
}

    /**
     * Show the form for creating a new resource.
     * 
     * Displays the form to create a new record.
     * 
     * @return \Illuminate\Contracts\View\View
     */
/*3- View Add page*/
public function create() {
    /*COMPACT_QUERY*/
return view('skills.create', /*COMPACT*/);
}


    /**
     * Show the form for editing the specified resource.
     * 
     * Displays the form to edit an existing record.
     * 
     * @param int $id
     * @return \Illuminate\Contracts\View\View
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
/*4- View update page*/
public function edit($id) {
    $row = Skill::findOrFail($id);

/*COMPACT_QUERY*/


return view('skills.edit', ['row' => $row], /*COMPACT*//*COMPACT_UPDATE*/);
}

    /**
     * Update the specified resource in storage.
     * 
     * Validates the request data and updates an existing record in the database.
     * 
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
/*5- validate and update data into database*/
public function update(Request $request, $id) {
$dbs_skills = view()->shared('dbs_skills');

$validator = \Validator::make($request->all(), [
           'name'=>$dbs_skills["name_validateas"].str_replace('NULL_ID',$id,$dbs_skills["name_unique_for_update"]),

           'description'=>$dbs_skills["description_validateas"].str_replace('NULL_ID',$id,$dbs_skills["description_unique_for_update"]),

           'status'=>$dbs_skills["status_validateas"].str_replace('NULL_ID',$id,$dbs_skills["status_unique_for_update"]),


]);




if ($validator->passes()) {
$table = Skill::findOrFail($id);
            $table->name = $request->input('name');
            $table->description = $request->input('description');
            $table->status = $request->input('status');

$table->update();

$max_id = $id;
/*DeleteCHECKBOXQUERY*/
/*CHECKBOXQUERY*/

return response()->json(['success' => 'Record has been updated successfully.']);
}
return response()->json(['error' => $validator->errors()]);
}

    /**
     * Remove the specified resource from storage.
     * 
     * Soft deletes the specified record (can be restored later).
     * 
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
/*6- delete record from database*/
public function destroy($id) {
$row = Skill::findOrFail($id);
$row->delete();
return response()->json(['success' => 'Record has been deleted successfully. You can restore it using the restore button.']);
}

    /**
     * Remove multiple resources from storage.
     * 
     * Soft deletes multiple records specified by comma-separated IDs.
     * 
     * @param string $ids Comma-separated list of IDs
     * @return \Illuminate\Http\JsonResponse
     */
/*7- delete all record from database*/
public function destroyAll($ids) {
$ids_arr = explode(',', $ids);
Skill::whereIn('id', $ids_arr)->delete();
return response()->json(['success' => 'Selected records have been deleted successfully. You can restore them using the restore button.']);
}

    /**
     * Restore a soft-deleted resource.
     * 
     * Restores a previously soft-deleted record.
     * 
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
/*8- restore record from database*/
public function restore($id) {
$row = Skill::withTrashed()->findOrFail($id);
$row->restore();
return response()->json(['success' => 'Record has been restored successfully.']);
}

/*9- delete multiple image*/


    /**
     * Export data to Excel/CSV format.
     * 
     * Downloads the resource data as a CSV file.
     * 
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
/*10- export csv*/
public function exportExcel()
{
    return Excel::download(new SkillExport, 'Skill.csv');
}

/*11- import csv*/

public function importCsv(Request $request)
{
    $request->validate([
        'file' => 'required|file|mimes:csv,txt',
    ]);

    $dbs_skills = view()->shared('dbs_skills');
    $importable = ['name','description','status'];
    $pictureFields = [''];
    $relationMaps = array (
);
    $rules = [];
    foreach ($importable as $f) {
        if (!isset($dbs_skills["${f}_validateas"])) {
            continue;
        }
        $rules[$f] = $dbs_skills["${f}_validateas"] . ($dbs_skills["${f}_unique"] ?? '');
    }
    // Multi dropdown fields store comma-separated IDs; validate via mapping, not Laravel rule string
    foreach ($relationMaps as $m) {
        if (!empty($m['multiple']) && isset($rules[$m['field']])) {
            unset($rules[$m['field']]);
        }
    }
    // Picture fields are imported as URL/path strings; skip image64 validator in CSV import.
    foreach ($pictureFields as $pf) {
        if (isset($rules[$pf])) { unset($rules[$pf]); }
    }

    $path = $request->file('file')->getRealPath();
    if (!$path) {
        return redirect()->back()->with('error', 'Invalid file.');
    }

    $handle = fopen($path, 'r');
    if (!$handle) {
        return redirect()->back()->with('error', 'Unable to read file.');
    }

    $header = fgetcsv($handle);
    if (!$header) {
        fclose($handle);
        return redirect()->back()->with('error', 'Empty CSV file.');
    }

    // Normalize headings
    $header = array_map(function($h) {
        $h = trim((string) $h);
        $h = strtolower(str_replace(' ', '_', $h));
        return $h;
    }, $header);
    // Drop Sr. column if present
    if (isset($header[0]) && in_array($header[0], ['sr.', 'sr', '#'], true)) {
        array_shift($header);
    }

    // Allow friendly headings from exported CSV (e.g. "client" => "client_id")
    $aliases = [];
    foreach ($relationMaps as $m) {
        if (empty($m['field'])) { continue; }
        $f = (string) $m['field'];
        $aliases[$f] = $f;
        if (substr($f, -3) === '_id') {
            $aliases[substr($f, 0, -3)] = $f;
        }
    }

    // Read all rows first (so we can resolve relations in bulk)
    $rows = [];
    $rowNumber = 1; // header is row 1
    while (($row = fgetcsv($handle)) !== false) {
        $rowNumber++;
        if (count($row) === 0) { continue; }
        if (count($row) > count($header) && count($header) > 0) {
            array_shift($row); // assume first col is Sr.
        }
        $data = [];
        foreach ($header as $idx => $key) {
            if (!isset($row[$idx])) { continue; }
            $mappedKey = $key;
            if (!in_array($mappedKey, $importable, true)) {
                if (isset($aliases[$mappedKey]) && in_array($aliases[$mappedKey], $importable, true)) {
                    $mappedKey = $aliases[$mappedKey];
                } else {
                    continue;
                }
            }
            $val = $row[$idx];
            if (is_string($val)) { $val = trim($val); }
            // Normalize empty strings to null (prevents '' into integer/date columns)
            if ($val === '') { $val = null; }
            $data[$mappedKey] = $val;
        }
        if (!empty($data)) {
            $rows[] = ['n' => $rowNumber, 'data' => $data];
        }
    }
    fclose($handle);

    // Bulk resolve relations: value in CSV is TEXT, store ID(s) in main
    foreach ($relationMaps as $m) {
        $field = $m['field'];
        $relTable = $m['table'];
        $relId = $m['id'];
        $relText = $m['text'];
        $isMultiple = !empty($m['multiple']);

        // collect unique names + numeric IDs from CSV
        $names = [];
        $numericIds = [];
        foreach ($rows as $r) {
            if (!array_key_exists($field, $r['data'])) { continue; }
            $raw = (string) ($r['data'][$field] ?? '');
            if ($raw === '') { continue; }
            if ($isMultiple) {
                foreach (array_filter(array_map('trim', explode(',', $raw))) as $one) {
                    if ($one === '') { continue; }
                    if (preg_match('/^\d+$/', $one)) {
                        $numericIds[$one] = true;
                    } else {
                        $names[$one] = true;
                    }
                }
            } else {
                $one = trim($raw);
                if ($one === '') { continue; }
                if (preg_match('/^\d+$/', $one)) {
                    $numericIds[$one] = true;
                } else {
                    $names[$one] = true;
                }
            }
        }
        $names = array_keys(array_filter($names, function($k){ return trim((string)$k) !== ''; }, ARRAY_FILTER_USE_KEY));
        $numericIds = array_keys(array_filter($numericIds, function($k){ return trim((string)$k) !== ''; }, ARRAY_FILTER_USE_KEY));
        if (empty($names) && empty($numericIds)) { continue; }

        // 1 query: existing map
        $existing = [];
        if (!empty($names)) {
            $existing = \DB::table($relTable)->whereIn($relText, $names)->pluck($relId, $relText)->toArray();
        }
        $validIds = [];
        if (!empty($numericIds)) {
            // Validate numeric ids exist (prevents importing invalid FK ids)
            $validIds = \DB::table($relTable)->whereIn($relId, $numericIds)->pluck($relId)->toArray();
            $validIds = array_fill_keys(array_map('strval', $validIds), true);
        }
        $missing = !empty($names) ? array_values(array_diff($names, array_keys($existing))) : [];

        // 1 query: insert missing (batch) (ignore failures; we'll re-fetch)
        if (!empty($missing)) {
            $ins = [];
            $hasCreated = \Schema::hasColumn($relTable, 'created_at');
            $hasUpdated = \Schema::hasColumn($relTable, 'updated_at');
            $now = now();
            foreach ($missing as $nm) {
                $row = [$relText => $nm];
                if ($hasCreated) { $row['created_at'] = $now; }
                if ($hasUpdated) { $row['updated_at'] = $now; }
                $ins[] = $row;
            }
            try {
                \DB::table($relTable)->insert($ins);
            } catch (\Throwable $e) {
                // ignore (unique constraints may race); we'll re-fetch
            }
            // 1 query: refresh map
            $existing = \DB::table($relTable)->whereIn($relText, $names)->pluck($relId, $relText)->toArray();
        }

        // replace text values with ids in rows
        foreach ($rows as &$r) {
            if (!array_key_exists($field, $r['data'])) { continue; }
            $raw = (string) ($r['data'][$field] ?? '');
            if ($raw === '') { $r['data'][$field] = null; continue; }
            if ($isMultiple) {
                $ids = [];
                foreach (array_filter(array_map('trim', explode(',', $raw))) as $nm) {
                    if ($nm === '') { continue; }
                    if (preg_match('/^\d+$/', $nm)) {
                        if (isset($validIds[(string)$nm])) { $ids[] = (string) $nm; }
                        continue;
                    }
                    if (isset($existing[$nm])) { $ids[] = (string) $existing[$nm]; }
                }
                $r['data'][$field] = !empty($ids) ? implode(',', $ids) : null;
            } else {
                $nm = trim($raw);
                if (preg_match('/^\d+$/', $nm)) {
                    $r['data'][$field] = isset($validIds[(string)$nm]) ? (int) $nm : null;
                } else {
                    $r['data'][$field] = isset($existing[$nm]) ? $existing[$nm] : null;
                }
            }
        }
        unset($r);
    }

    // Validate + batch insert main table
    $count = 0;
    $batch = [];
    $batchSize = 500;
    $hasCreatedMain = \Schema::hasColumn('skills', 'created_at');
    $hasUpdatedMain = \Schema::hasColumn('skills', 'updated_at');
    $now = now();

    foreach ($rows as $r) {
        $data = $r['data'];
        $n = $r['n'];

        // Picture import from URL: download into public/images/Y/m/d and store relative path.
        foreach ($pictureFields as $pf) {
            if (!array_key_exists($pf, $data) || empty($data[$pf])) { continue; }
            $pv = (string) $data[$pf];
            if (preg_match('/^https?:\/\//i', $pv)) {
                $urlPath = parse_url($pv, PHP_URL_PATH);
                $ext = strtolower((string) pathinfo((string) $urlPath, PATHINFO_EXTENSION));
                if ($ext === '') { $ext = 'jpg'; }
                $safeExt = preg_replace('/[^a-z0-9]/i', '', $ext);
                if ($safeExt === '') { $safeExt = 'jpg'; }
                $currentDate = now();
                $storagePath = $currentDate->year . '/' . $currentDate->month . '/' . $currentDate->day . '/';
                $dir = public_path('images/' . $storagePath);
                if (!is_dir($dir)) { @mkdir($dir, 0755, true); }
                $filename = uniqid('img_') . '.' . $safeExt;
                $context = stream_context_create(['http' => ['timeout' => 10], 'https' => ['timeout' => 10]]);
                $bin = @file_get_contents($pv, false, $context);
                if ($bin === false || $bin === '') {
                    $msg = 'CSV row ' . $n . ' picture URL not accessible: ' . $pv;
                    if ($request->ajax() || $request->expectsJson()) {
                        return response()->json(['error' => $msg], 422);
                    }
                    return redirect()->back()->with('error', $msg);
                }
                if (@file_put_contents($dir . $filename, $bin) === false) {
                    $msg = 'CSV row ' . $n . ' picture save failed.';
                    if ($request->ajax() || $request->expectsJson()) {
                        return response()->json(['error' => $msg], 422);
                    }
                    return redirect()->back()->with('error', $msg);
                }
                $data[$pf] = $storagePath . $filename;
            }
        }

        $v = \Validator::make($data, $rules);
        if ($v->fails()) {
            $first = \implode(' ', \array_map(function($arr){ return is_array($arr) ? ($arr[0] ?? '') : (string)$arr; }, $v->errors()->toArray()));
            $msg = 'CSV row ' . $n . ' validation failed: ' . $first;
            if ($request->ajax() || $request->expectsJson()) {
                return response()->json(['error' => $msg], 422);
            }
            return redirect()->back()->with('error', $msg);
        }

        if ($hasCreatedMain && !isset($data['created_at'])) { $data['created_at'] = $now; }
        if ($hasUpdatedMain && !isset($data['updated_at'])) { $data['updated_at'] = $now; }
        $batch[] = $data;
        if (count($batch) >= $batchSize) {
            try { \DB::table('skills')->insert($batch); } catch (\Throwable $e) {
                $msg = 'CSV batch insert failed near row ' . $n . ': ' . $e->getMessage();
                if ($request->ajax() || $request->expectsJson()) {
                    return response()->json(['error' => $msg], 422);
                }
                return redirect()->back()->with('error', $msg);
            }
            $count += count($batch);
            $batch = [];
        }
    }
    if (!empty($batch)) {
        try { \DB::table('skills')->insert($batch); } catch (\Throwable $e) {
            $msg = 'CSV batch insert failed: ' . $e->getMessage();
            if ($request->ajax() || $request->expectsJson()) {
                return response()->json(['error' => $msg], 422);
            }
            return redirect()->back()->with('error', $msg);
        }
        $count += count($batch);
    }

    $msg = "Imported {$count} row(s) successfully.";
    if ($request->ajax() || $request->expectsJson()) {
        return response()->json(['success' => $msg, 'count' => $count]);
    }
    return redirect()->back()->with('success', $msg);
}



}
