<?php
include 'includes/db.php';

$msg = "";
$msg_class = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Basic Fields
    $first_name = htmlspecialchars(trim($_POST['first_name']));
    $middle_name = htmlspecialchars(trim($_POST['middle_name']));
    $last_name = htmlspecialchars(trim($_POST['last_name']));
    $mobile = htmlspecialchars(trim($_POST['mobile']));
    $email = htmlspecialchars(trim($_POST['email']));
    $address = htmlspecialchars(trim($_POST['address']));
    $pincode = htmlspecialchars(trim($_POST['pincode']));

    $district = htmlspecialchars(trim($_POST['district']));
    $state = htmlspecialchars(trim($_POST['state']));
    


    $valid = true;
    if (!preg_match('/^[0-9]{10}$/', $mobile)) {
        $msg = "Error: Mobile number must be 10 digits.";
        $msg_class = "alert-danger";
        $valid = false;
    }

    if ($valid) {
        $check = $conn->prepare("SELECT id FROM job_applications WHERE email = ? OR mobile = ?");
        $check->bind_param("ss", $email, $mobile);
        $check->execute();
        $check->store_result();
        if ($check->num_rows > 0) {
            $msg = "Error: Application with this Email or Mobile already exists.";
            $msg_class = "alert-danger";
            $valid = false;
        }
        $check->close();
    }

    if ($valid) {
        $resume_path = "";
        if (isset($_FILES['resume']) && $_FILES['resume']['error'] == 0) {
            $target_dir = "uploads/resumes/";
            if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);
            
            $file_ext = strtolower(pathinfo($_FILES["resume"]["name"], PATHINFO_EXTENSION));
            $allowed = ['pdf', 'doc', 'docx'];
            
            if (in_array($file_ext, $allowed)) {
                $new_filename = uniqid() . '_' . $first_name . '.' . $file_ext;
                $target_file = $target_dir . $new_filename;
                if (move_uploaded_file($_FILES["resume"]["tmp_name"], $target_file)) {
                    $resume_path = $target_file;
                } else {
                    $msg = "Failed to upload resume.";
                    $msg_class = "alert-danger";
                    $valid = false;
                }
            } else {
                $msg = "Invalid file type. Only PDF/DOC allowed.";
                $msg_class = "alert-danger";
                $valid = false;
            }
        } else {
            $msg = "Please upload a resume.";
            $msg_class = "alert-danger";
            $valid = false;
        }

        if ($valid) {
            $stmt = $conn->prepare("INSERT INTO job_applications (first_name, middle_name, last_name, mobile, email, address, district, state, pincode, resume_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssssssss", $first_name, $middle_name, $last_name, $mobile, $email, $address, $district, $state, $pincode, $resume_path);
            
            if ($stmt->execute()) {
                $msg = "Application Submitted Successfully!";
                $msg_class = "alert-success";
            } else {
                $msg = "Database Error: " . $conn->error;
                $msg_class = "alert-danger";
            }
        }
    }
}

include 'includes/header.php';
?>

<!-- FontAwesome & Google Fonts -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">

<style>
    /* Updated to BLUE Theme as requested */
    :root {
        --primary-blue: #160aeaff; /* Standard Blue */
        --dark-blue: #0a0a90;
        --dark-text: #2d3436;
        --light-bg: #e3f2fd;
        --border-color: #bbdefb;
    }

    body { background-color: #f0f7ff; }

    .careers-hero {
        background: linear-gradient(135deg, #0a0a90 0%, #0a0a90 100%);
        color: white;
        padding: 60px 0;
        text-align: center;
    }
    
    .form-section-title {
        font-family: 'Poppins', sans-serif;
        font-size: 18px;
        font-weight: 600;
        color: var(--dark-blue);
        margin-bottom: 20px;
        display: flex;
        align-items: center;
        gap: 10px;
        border-bottom: 2px solid var(--primary-blue);
        padding-bottom: 10px;
        width: 100%;
    }
    
    .modern-form-container {
        max-width: 900px;
        margin: -50px auto 50px;
        background: white;
        border-radius: 15px;
        box-shadow: 0 10px 30px rgba(0, 123, 255, 0.1);
        padding: 40px;
        position: relative;
        z-index: 10;
        border-top: 5px solid var(--primary-blue);
    }

    .form-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 25px; }
    .form-group { margin-bottom: 20px; position: relative; }
    .form-group label { display: block; font-family: 'Poppins', sans-serif; font-weight: 500; font-size: 14px; margin-bottom: 8px; color: #444; }
    .form-group label span.required { color: red; }

    .input-wrapper { display: flex; align-items: center; }
    
    /* Input Styling with padding for button */
    .form-control-modern {
        width: 100%;
        padding: 12px 15px;
        border: 1px solid #ced4da;
        border-radius: 6px;
        font-size: 14px;
        font-family: 'Poppins', sans-serif;
        transition: 0.3s;
    }
    .form-control-modern:focus { border-color: var(--primary-blue); box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.2); outline: none; }


    
    .btn-submit {
        background: var(--primary-blue); color: white; border: none; padding: 15px 40px; border-radius: 6px;
        font-size: 16px; font-weight: 600; text-transform: uppercase; cursor: pointer; width: 100%;
        display: flex; justify-content: center; align-items: center; gap: 10px; transition: 0.3s;
    }
    .btn-submit:hover { background: var(--dark-blue); transform: translateY(-2px); }
    
    /* Responsive */
    @media (max-width: 768px) { .form-grid { grid-template-columns: 1fr; } .modern-form-container { padding: 20px; } }
    
    .alert-box { padding: 15px; border-radius: 6px; margin-bottom: 25px; text-align: center; }
    .alert-danger { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
</style>



    <div class="careers-hero">
        <h1>Application Form  <br></h1>
        <br>
        <p><br> <br></p>
    </div>

    <div class="container">
        <div class="modern-form-container">
            <?php if(!empty($msg)) echo "<div class='alert-box $msg_class'>$msg</div>"; ?>

            <form method="POST" enctype="multipart/form-data">
                
                <div class="form-section-title"><i class="fas fa-user-circle"></i> Personal Information</div>

                <div class="form-grid">
                    <div class="form-group"><label>First Name <span class="required">*</span></label><input type="text" name="first_name" class="form-control-modern" required></div>
                    <div class="form-group"><label>Middle Name</label><input type="text" name="middle_name" class="form-control-modern"></div>
                    <div class="form-group"><label>Last Name <span class="required">*</span></label><input type="text" name="last_name" class="form-control-modern" required></div>
                </div>

                <div class="form-grid" style="grid-template-columns: 1fr 1fr;">
                    <div class="form-group">
                        <label>Mobile Number <span class="required">*</span></label>
                        <div class="input-wrapper">
                            <span class="mobile-prefix">+91</span>
                            <input type="text" name="mobile" class="form-control-modern mobile-input" placeholder="10 digit number" pattern="[0-9]{10}" required maxlength="10">
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Email Address <span class="required">*</span></label>
                        <input type="email" name="email" class="form-control-modern" placeholder="user@example.com" required>
                    </div>
                </div>

                <div class="form-section-title" style="margin-top: 30px;"><i class="fas fa-map-marker-alt"></i> Address Details</div>
                <div class="form-group"><label>Full Address <span class="required">*</span></label><input type="text" name="address" class="form-control-modern" placeholder="House No, Ward No, Village/Mohalla" required></div>

                <div class="form-grid">
                    <!-- State -->
                    <div class="form-group">
                        <label>State <span class="required">*</span></label>
                        <select name="state" id="ddlState" class="form-control-modern" onchange="loadDistricts()" required>
                           <option value="">Select State</option>
                            
                        </select>
                    </div>

                    <!-- District (Dependent) -->
                    <div class="form-group">
                        <label>District <span class="required">*</span></label>
                        <select name="district" id="ddlDistrict" class="form-control-modern" required disabled>
                            <option value="">Select District</option>
                        </select>
                    </div>
    


                    <!-- Pin Code -->
                    <div class="form-group">
                        <label>Pin Code <span class="required">*</span></label>
                        <input type="text" name="pincode" class="form-control-modern" placeholder="6 digit Pin Code" pattern="[0-9]{6}" maxlength="6" required oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 6);">
                    </div>
                </div>

<script>
    // Data for Cascading Dropdowns
    const data = {
"Andhra Pradesh":["Anantapur","Chittoor","East Godavari","Guntur","Kadapa","Krishna","Kurnool","Nellore","Prakasam","Srikakulam","Visakhapatnam","Vizianagaram","West Godavari"],
"Arunachal Pradesh":["Tawang","West Kameng","East Kameng","Papum Pare","Lower Subansiri","Upper Subansiri","West Siang","East Siang","Siang","Lower Dibang Valley","Upper Dibang Valley","Anjaw","Lohit","Namsai","Changlang","Tirap","Longding"],
"Assam":["Baksa","Barpeta","Biswanath","Bongaigaon","Cachar","Charaideo","Chirang","Darrang","Dhemaji","Dhubri","Dibrugarh","Dima Hasao","Goalpara","Golaghat","Hailakandi","Hojai","Jorhat","Kamrup","Kamrup Metro","Karbi Anglong","Kokrajhar","Lakhimpur","Majuli","Morigaon","Nagaon","Nalbari","Sivasagar","Sonitpur","South Salmara","Tinsukia","Udalguri","West Karbi Anglong"],
"Bihar":["Araria","Arwal","Aurangabad","Banka","Begusarai","Bhagalpur","Bhojpur","Buxar","Darbhanga","East Champaran","Gaya","Gopalganj","Jamui","Jehanabad","Kaimur","Katihar","Khagaria","Kishanganj","Lakhisarai","Madhepura","Madhubani","Munger","Muzaffarpur","Nalanda","Nawada","Patna","Purnia","Rohtas","Saharsa","Samastipur","Saran","Sheikhpura","Sheohar","Sitamarhi","Siwan","Supaul","Vaishali","West Champaran"],
"Chhattisgarh":["Balod","Baloda Bazar","Balrampur","Bastar","Bemetara","Bijapur","Bilaspur","Dantewada","Dhamtari","Durg","Gariaband","Gaurela Pendra Marwahi","Janjgir Champa","Jashpur","Kabirdham","Kanker","Kondagaon","Korba","Koriya","Mahasamund","Mungeli","Narayanpur","Raigarh","Raipur","Rajnandgaon","Sukma","Surajpur","Surguja"],
"Goa":["North Goa","South Goa"],
"Gujarat":["Ahmedabad","Amreli","Anand","Aravalli","Banaskantha","Bharuch","Bhavnagar","Botad","Chhota Udaipur","Dahod","Dang","Devbhoomi Dwarka","Gandhinagar","Gir Somnath","Jamnagar","Junagadh","Kheda","Kutch","Mahisagar","Mehsana","Morbi","Narmada","Navsari","Panchmahal","Patan","Porbandar","Rajkot","Sabarkantha","Surat","Surendranagar","Tapi","Vadodara","Valsad"],
"Haryana":["Ambala","Bhiwani","Charkhi Dadri","Faridabad","Fatehabad","Gurugram","Hisar","Jhajjar","Jind","Kaithal","Karnal","Kurukshetra","Mahendragarh","Nuh","Palwal","Panchkula","Panipat","Rewari","Rohtak","Sirsa","Sonipat","Yamunanagar"],
"Himachal Pradesh":["Bilaspur","Chamba","Hamirpur","Kangra","Kinnaur","Kullu","Lahaul Spiti","Mandi","Shimla","Sirmaur","Solan","Una"],
"Jharkhand":["Bokaro","Chatra","Deoghar","Dhanbad","Dumka","East Singhbhum","Garhwa","Giridih","Godda","Gumla","Hazaribagh","Jamtara","Khunti","Koderma","Latehar","Lohardaga","Pakur","Palamu","Ramgarh","Ranchi","Sahebganj","Seraikela Kharsawan","Simdega","West Singhbhum"],
"Karnataka":["Bagalkot","Ballari","Belagavi","Bengaluru Rural","Bengaluru Urban","Bidar","Chamarajanagar","Chikkaballapur","Chikkamagaluru","Chitradurga","Dakshina Kannada","Davanagere","Dharwad","Gadag","Hassan","Haveri","Kalaburagi","Kodagu","Kolar","Koppal","Mandya","Mysuru","Raichur","Ramanagara","Shivamogga","Tumakuru","Udupi","Uttara Kannada","Vijayapura","Yadgir"],
"Kerala":["Alappuzha","Ernakulam","Idukki","Kannur","Kasaragod","Kollam","Kottayam","Kozhikode","Malappuram","Palakkad","Pathanamthitta","Thiruvananthapuram","Thrissur","Wayanad"],
"Madhya Pradesh":["Agar Malwa","Alirajpur","Anuppur","Ashoknagar","Balaghat","Barwani","Betul","Bhind","Bhopal","Burhanpur","Chhatarpur","Chhindwara","Damoh","Datia","Dewas","Dhar","Dindori","Guna","Gwalior","Harda","Hoshangabad","Indore","Jabalpur","Jhabua","Katni","Khandwa","Khargone","Mandla","Mandsaur","Morena","Narsinghpur","Neemuch","Panna","Raisen","Rajgarh","Ratlam","Rewa","Sagar","Satna","Sehore","Seoni","Shahdol","Shajapur","Sheopur","Shivpuri","Sidhi","Singrauli","Tikamgarh","Ujjain","Umaria","Vidisha"],
"Maharashtra":["Ahmednagar","Akola","Amravati","Aurangabad","Beed","Bhandara","Buldhana","Chandrapur","Dhule","Gadchiroli","Gondia","Hingoli","Jalgaon","Jalna","Kolhapur","Latur","Mumbai City","Mumbai Suburban","Nagpur","Nanded","Nandurbar","Nashik","Osmanabad","Palghar","Parbhani","Pune","Raigad","Ratnagiri","Sangli","Satara","Sindhudurg","Solapur","Thane","Wardha","Washim","Yavatmal"],
"Manipur":["Bishnupur","Chandel","Churachandpur","Imphal East","Imphal West","Jiribam","Kakching","Kamjong","Kangpokpi","Noney","Pherzawl","Senapati","Tamenglong","Tengnoupal","Thoubal","Ukhrul"],
"Meghalaya":["East Garo Hills","East Khasi Hills","Jaintia Hills","North Garo Hills","Ri Bhoi","South Garo Hills","South West Garo Hills","South West Khasi Hills","West Garo Hills","West Khasi Hills"],
"Mizoram":["Aizawl","Champhai","Kolasib","Lawngtlai","Lunglei","Mamit","Saiha","Serchhip","Khawzawl","Hnahthial","Saitual"],
"Nagaland":["Dimapur","Kiphire","Kohima","Longleng","Mokokchung","Mon","Peren","Phek","Tuensang","Wokha","Zunheboto"],
"Odisha":["Angul","Balangir","Balasore","Bargarh","Bhadrak","Boudh","Cuttack","Deogarh","Dhenkanal","Gajapati","Ganjam","Jagatsinghpur","Jajpur","Jharsuguda","Kalahandi","Kandhamal","Kendrapara","Kendujhar","Khordha","Koraput","Malkangiri","Mayurbhanj","Nabarangpur","Nayagarh","Nuapada","Puri","Rayagada","Sambalpur","Subarnapur","Sundargarh"],
"Punjab":["Amritsar","Barnala","Bathinda","Faridkot","Fatehgarh Sahib","Fazilka","Ferozepur","Gurdaspur","Hoshiarpur","Jalandhar","Kapurthala","Ludhiana","Malerkotla","Mansa","Moga","Mohali","Muktsar","Pathankot","Patiala","Rupnagar","Sangrur","Shaheed Bhagat Singh Nagar","Tarn Taran"],
"Rajasthan":["Ajmer","Alwar","Banswara","Baran","Barmer","Bharatpur","Bhilwara","Bikaner","Bundi","Chittorgarh","Churu","Dausa","Dholpur","Dungarpur","Hanumangarh","Jaipur","Jaisalmer","Jalore","Jhalawar","Jhunjhunu","Jodhpur","Karauli","Kota","Nagaur","Pali","Pratapgarh","Rajsamand","Sawai Madhopur","Sikar","Sirohi","Sri Ganganagar","Tonk","Udaipur"],
"Sikkim":["East Sikkim","North Sikkim","South Sikkim","West Sikkim"],
"Tamil Nadu":["Ariyalur","Chengalpattu","Chennai","Coimbatore","Cuddalore","Dharmapuri","Dindigul","Erode","Kallakurichi","Kanchipuram","Kanyakumari","Karur","Krishnagiri","Madurai","Nagapattinam","Namakkal","Nilgiris","Perambalur","Pudukkottai","Ramanathapuram","Ranipet","Salem","Sivaganga","Tenkasi","Thanjavur","Theni","Thoothukudi","Tiruchirappalli","Tirunelveli","Tirupathur","Tiruppur","Tiruvallur","Tiruvannamalai","Tiruvarur","Vellore","Viluppuram","Virudhunagar"],
"Telangana":["Adilabad","Bhadradri Kothagudem","Hyderabad","Jagtial","Jangaon","Jayashankar Bhupalpally","Jogulamba Gadwal","Kamareddy","Karimnagar","Khammam","Komaram Bheem","Mahabubabad","Mahabubnagar","Mancherial","Medak","Medchal Malkajgiri","Mulugu","Nagarkurnool","Nalgonda","Narayanpet","Nirmal","Nizamabad","Peddapalli","Rajanna Sircilla","Ranga Reddy","Sangareddy","Siddipet","Suryapet","Vikarabad","Wanaparthy","Warangal Rural","Warangal Urban","Yadadri Bhuvanagiri"],
"Tripura":["Dhalai","Gomati","Khowai","North Tripura","Sepahijala","South Tripura","Unakoti","West Tripura"],
"Uttar Pradesh":["Agra","Aligarh","Ambedkar Nagar","Amethi","Amroha","Auraiya","Ayodhya","Azamgarh","Baghpat","Bahraich","Ballia","Balrampur","Banda","Barabanki","Bareilly","Basti","Bhadohi","Bijnor","Budaun","Bulandshahr","Chandauli","Chitrakoot","Deoria","Etah","Etawah","Farrukhabad","Fatehpur","Firozabad","Gautam Buddha Nagar","Ghaziabad","Ghazipur","Gonda","Gorakhpur","Hamirpur","Hapur","Hardoi","Hathras","Jalaun","Jaunpur","Jhansi","Kannauj","Kanpur Dehat","Kanpur Nagar","Kasganj","Kaushambi","Kheri","Kushinagar","Lalitpur","Lucknow","Maharajganj","Mahoba","Mainpuri","Mathura","Mau","Meerut","Mirzapur","Moradabad","Muzaffarnagar","Pilibhit","Pratapgarh","Prayagraj","Raebareli","Rampur","Saharanpur","Sambhal","Sant Kabir Nagar","Shahjahanpur","Shamli","Shravasti","Siddharthnagar","Sitapur","Sonbhadra","Sultanpur","Unnao","Varanasi"],
"Uttarakhand":["Almora","Bageshwar","Chamoli","Champawat","Dehradun","Haridwar","Nainital","Pauri Garhwal","Pithoragarh","Rudraprayag","Tehri Garhwal","Udham Singh Nagar","Uttarkashi"],
"West Bengal":["Alipurduar","Bankura","Birbhum","Cooch Behar","Dakshin Dinajpur","Darjeeling","Hooghly","Howrah","Jalpaiguri","Jhargram","Kalimpong","Kolkata","Malda","Murshidabad","Nadia","North 24 Parganas","Paschim Bardhaman","Paschim Medinipur","Purba Bardhaman","Purba Medinipur","Purulia","South 24 Parganas","Uttar Dinajpur"]
};

    function loadStates() {
        const stateSel = document.getElementById("ddlState");
        // Keep the first option (Select State)
        stateSel.length = 1; 

        for (let state in data) {
            let option = document.createElement("option");
            option.value = state;
            option.text = state;
            stateSel.add(option);
        }
        
        // Add Other option
        let optionOther = document.createElement("option");
        optionOther.value = "Other";
        optionOther.text = "Other";
        stateSel.add(optionOther);
    }

    // Call immediately to populate
    loadStates();

    function loadDistricts() {
        const stateSel = document.getElementById("ddlState");
        const districtSel = document.getElementById("ddlDistrict");
        
        const selectedState = stateSel.value;
        
        // Reset District
        districtSel.innerHTML = '<option value="">---Select District---</option>';
        districtSel.disabled = true;

        if (selectedState && data[selectedState]) {
            districtSel.disabled = false;
            // Populate Districts
            // Change: iterate over array directly since data[selectedState] is now an array
            data[selectedState].forEach(function(district) {
                let option = document.createElement("option");
                option.value = district;
                option.text = district;
                districtSel.add(option);
            });
        } else if (selectedState === "Other") {
            // Allow manual toggle or show text input (simplified here)
             districtSel.disabled = false;
             let option = document.createElement("option");
             option.value = "Other";
             option.text = "Other";
             districtSel.add(option);
        }
    }


</script>

                <div class="form-section-title" style="margin-top: 30px;"><i class="fas fa-file-upload"></i> Documents</div>
                <div class="form-group">
                    <label>Resume (PDF, DOC) <span class="required">*</span></label>
                    <div style="border: 2px dashed #007bff; padding: 20px; text-align: center; border-radius: 6px; background: #f0f7ff;">
                        <input type="file" name="resume" required style="display: block; margin: 0 auto;">
                    </div>
                </div>

                <div style="margin-top: 40px;">
                    <button type="submit" class="btn-submit"><i class="fas fa-paper-plane"></i> Submit Application</button>
                </div>
            </form>
        </div>
    </div>

<?php include 'includes/footer.php'; ?>
