<?php

namespace App\Validations;

use App\Constants\Constants;
use PhpOffice\PhpSpreadsheet\Shared\Date as PhpSpreadsheetDate;

class Validation
{

    public static function validationForAdmin(array $data)
    {
        if (empty($data['username'])) {
            return response()->json([
                "message" => "Please enter username",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }

        if (empty($data['password'])) {
            return response()->json([
                "message" => "Please enter password",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }

        if (empty($data['email'])) {
            return response()->json([
                "message" => "Please enter email",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }

        if (empty($data['email'])) {
            return response()->json([
                "message" => "Please enter email",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }

        if (empty($data['mobile_number'])) {
            return response()->json([
                "message" => "Please enter mobile number",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }

        if (empty($data['role'])) {
            return response()->json([
                "message" => "Please select a role",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }

        if (! in_array($data['role'], [
            'SUPER_ADMIN',
            'ADMIN',
            'MANAGER'
        ])) {
            return response()->json([
                "message" => "Role must be one of 'SUPER_ADMIN', 'ADMIN', 'MANAGER'",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }

        return response()->json([
            "message" => "Validated successfully.",
            "status" => Constants::SUCCESS_CODE
        ], Constants::SUCCESS_CODE);
    }

    public static function validationForRationCard(array $data)
    {
        if (empty($data['ration_card_number'])) {
            return response()->json([
                "message" => "Please enter Ration Card Number.",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }

        if (empty($data['address'])) {
            return response()->json([
                "message" => "Please enter Address.",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }



        // if (empty($data['mobile_number'])) {
        //     return response()->json([
        //         "message" => "Please enter Mobile Number.",
        //         "status" => Constants::INVALID_PARAMS
        //     ], Constants::INVALID_PARAMS);
        // }

        // if (!preg_match('/^[0-9]{10}$/', $data['mobile_number'])) {
        //     return response()->json([
        //         "message" => "Mobile Number must be 10 digits.",
        //         "status" => Constants::INVALID_PARAMS
        //     ], Constants::INVALID_PARAMS);
        // }

        return response()->json([
            "message" => "Validated successfully.",
            "status" => Constants::SUCCESS_CODE
        ], Constants::SUCCESS_CODE);
    }

    public static function validationForBooth(array $data)
    {
        if (empty($data['booth_number'])) {
            return response()->json([
                "message" => "Please enter Booth Number.",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }

        if (empty($data['booth_address'])) {
            return response()->json([
                "message" => "Please enter Booth Address.",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }

        // Optional: Validate booth_number format (example: must be alphanumeric, max 10 chars)
       if (!preg_match('/^[A-Za-z0-9\-\/]{1,10}$/', $data['booth_number'])) {
    return response()->json([
        "message" => "Booth Number format is invalid. Only letters, numbers, hyphens, and slashes allowed (max 10 characters).",
        "status" => Constants::INVALID_PARAMS
    ], Constants::INVALID_PARAMS);
}

        // Optional: Validate streets array if provided
        if (isset($data['streets']) && $data['streets'] !== null) {
            if (!is_array($data['streets'])) {
                return response()->json([
                    "message" => "Streets must be an array.",
                    "status" => Constants::INVALID_PARAMS
                ], Constants::INVALID_PARAMS);
            }

            // Validate each street in the array
            foreach ($data['streets'] as $street) {
                if (!is_array($street) || !isset($street['id']) || !isset($street['name'])) {
                    return response()->json([
                        "message" => "Each street must have 'id' and 'name' properties.",
                        "status" => Constants::INVALID_PARAMS
                    ], Constants::INVALID_PARAMS);
                }
            }
        }

        return response()->json([
            "message" => "Validated successfully.",
            "status" => Constants::SUCCESS_CODE
        ], Constants::SUCCESS_CODE);
    }

   public static function validateGiftData($data)
{
    // Validate gift name
    if (empty($data['gift_name'])) {
        return response()->json([
            "message" => "Gift name is required and should not exceed 100 characters.",
            "status" => Constants::INVALID_PARAMS
        ], Constants::INVALID_PARAMS);
    }

    // Validate gift number
    // if (empty($data['gift_number']) || !is_numeric($data['gift_number']) || strlen($data['gift_number']) > 50) {
    //     return response()->json([
    //         "message" => "Gift number is required and must be a numeric value with a maximum length of 50 characters.",
    //         "status" => Constants::INVALID_PARAMS
    //     ], Constants::INVALID_PARAMS);
    // }

    // If all validations pass
    return response()->json([
        "message" => "Validated successfully.",
        "status" => Constants::SUCCESS_CODE
    ], Constants::SUCCESS_CODE); // Data is valid
}

public static function validationForStreet(array $data)
{
    if (empty($data['street_name'])) {
        return response()->json([
            "message" => "Please enter Street Name.",
            "status" => Constants::INVALID_PARAMS
        ], Constants::INVALID_PARAMS);
    }

    // Optional: name format validation (only letters, spaces, max 100 chars)
    // if (!preg_match('/^[A-Za-z0-9\s\-]{1,100}$/', $data['street_name'])) {
    //     return response()->json([
    //         "message" => "Street Name is invalid. Only letters, numbers, spaces, and hyphens allowed (max 100 characters).",
    //         "status" => Constants::INVALID_PARAMS
    //     ], Constants::INVALID_PARAMS);
    // }

    return response()->json([
        "message" => "Validated successfully.",
        "status" => Constants::SUCCESS_CODE
    ], Constants::SUCCESS_CODE);
}

// Validation for standalone voter creation
public static function validationForVoter(array $data)
{
    // Voter ID is required
    if (empty($data['voter_id_number'])) {
        return response()->json([
            "message" => "Please enter Voter ID Number.",
            "status" => Constants::INVALID_PARAMS
        ], Constants::INVALID_PARAMS);
    }

    // Name is required
    if (empty($data['name'])) {
        return response()->json([
            "message" => "Please enter Name.",
            "status" => Constants::INVALID_PARAMS
        ], Constants::INVALID_PARAMS);
    }

    // Validate name format: allow Unicode letters (including Tamil) and spaces
    // if (!preg_match('/^[\p{L}\s]+$/u', $data['name'])) {
    //     return response()->json([
    //         "message" => "Name must contain only letters and spaces.",
    //         "status" => Constants::INVALID_PARAMS
    //     ], Constants::INVALID_PARAMS);
    // }

    // Gender is required
    if (empty($data['gender'])) {
        return response()->json([
            "message" => "Please select Gender.",
            "status" => Constants::INVALID_PARAMS
        ], Constants::INVALID_PARAMS);
    }

    // Validate gender values
    if (!in_array($data['gender'], ['Male', 'Female', 'Other'])) {
        return response()->json([
            "message" => "Gender must be Male, Female, or Other.",
            "status" => Constants::INVALID_PARAMS
        ], Constants::INVALID_PARAMS);
    }

    // Require at least one of year_of_birth, date_of_birth or age to avoid DB constraint errors
    if (empty($data['year_of_birth']) && empty($data['date_of_birth']) && empty($data['age'])) {
        return response()->json([
            "message" => "Please provide Year of Birth, or Date of Birth (YYYY-MM-DD), or Age.",
            "status" => Constants::INVALID_PARAMS
        ], Constants::INVALID_PARAMS);
    }

    // Validate year of birth if provided. Accept either a 4-digit year or a full date (YYYY-MM-DD)
    if (!empty($data['year_of_birth'])) {
        $currentYear = date('Y');
        $yobRaw = trim($data['year_of_birth']);
        $year = null;

        // If value is a full date like YYYY-MM-DD, extract the year
        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $yobRaw)) {
            $year = (int) substr($yobRaw, 0, 4);
        } elseif (preg_match('/^\d{4}$/', $yobRaw)) {
            $year = (int) $yobRaw;
        } elseif (is_numeric($yobRaw)) {
            // Numeric values may be either a 4-digit year or an Excel date serial (e.g., 39742).
            $num = floatval($yobRaw);
            if ($num >= 1900 && $num <= (int)$currentYear) {
                // looks like a direct year
                $year = (int)$num;
            } elseif ($num > 31) {
                // likely an Excel serial date — convert to DateTime and extract year
                try {
                    $dt = PhpSpreadsheetDate::excelToDateTimeObject($num);
                    $year = (int)$dt->format('Y');
                } catch (\Exception $e) {
                    $year = null;
                }
            } else {
                // small numeric (like day of month) — treat as invalid year
                $year = null;
            }
        } else {
            // Try to parse other date formats (e.g., Excel or localized strings)
            $ts = strtotime($yobRaw);
            if ($ts !== false) {
                $year = (int) date('Y', $ts);
            }
        }

        if ($year === null) {
            return response()->json([
                "message" => "Year of Birth format is invalid. Provide a 4-digit year or YYYY-MM-DD.",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }

        if ($year < 1900 || $year > $currentYear) {
            return response()->json([
                "message" => "Year of Birth must be between 1900 and $currentYear.",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }
        // replace with normalized year so callers can rely on integer year
        $data['year_of_birth'] = $year;
    }

    // Validate mobile number if provided
    if (!empty($data['mobile_number'])) {
        if (!preg_match('/^[0-9]{10}$/', $data['mobile_number'])) {
            return response()->json([
                "message" => "Mobile Number must be 10 digits.",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }
    }

    // Validate Aadhar number if provided. Normalize by removing non-digit characters.
    if (isset($data['aadhar_number'])) {
        $aadharRaw = trim((string)$data['aadhar_number']);
        $aadharDigits = preg_replace('/\D+/', '', $aadharRaw);

        // treat empty (or non-digit) cell as not provided
        if ($aadharDigits === '') {
            unset($data['aadhar_number']);
        } else {
            if (!preg_match('/^[0-9]{12}$/', $aadharDigits)) {
                return response()->json([
                    "message" => "Aadhar Number must be exactly 12 digits.",
                    "status" => Constants::INVALID_PARAMS
                ], Constants::INVALID_PARAMS);
            }
            // normalize value for downstream use
            $data['aadhar_number'] = $aadharDigits;
        }
    }

   

    // Validate date of birth format if provided
    if (!empty($data['date_of_birth'])) {
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $data['date_of_birth'])) {
            return response()->json([
                "message" => "Date of Birth must be in YYYY-MM-DD format.",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }
    }

    // Validate anniversary date format if provided
    if (!empty($data['anniversary_date'])) {
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $data['anniversary_date'])) {
            return response()->json([
                "message" => "Anniversary Date must be in YYYY-MM-DD format.",
                "status" => Constants::INVALID_PARAMS
            ], Constants::INVALID_PARAMS);
        }
    }

    // Validation passed
    return response()->json([
        "message" => "Validated successfully.",
        "status" => Constants::SUCCESS_CODE
    ], Constants::SUCCESS_CODE);
}


}
