<?php
// Start session and include database configuration
session_start();
include 'config.php';

// Restrict access to superadmin and md roles
if (!isset($_SESSION['role']) || !in_array(strtolower($_SESSION['role']), ['superadmin', 'md'])) {
    header("Location: dashboard.php");
    exit();
}

function createUser($conn) {
    $fields = [
        'id', 'first_name', 'last_name', 'username', 'password', 'role', 'email', 'mobileno', 'address', 'pancard',
        'aadharcard', 'designation', 'division', 'marital_status', 'anniversary_date', 'gender', 'date_of_birth',
        'date_of_joining', 'father_name', 'spouse_name', 'qualification',
        'previous_experience', 'company_name', 'last_company_1', 'last_company_1_years', 'last_company_1_salary',
        'total_experience_years', 'previous_salary', 'uan_no', 'bloodgroup', 'esic_no',
        'bank_name', 'account_number', 'ifsc_code', 'responsibilities', 'level', 'appointment_type', 'location',
        'basic_salary', 'kpi', 'emergency_contact_no', 'emergency_contact_person', 'emergency_contact_relationship'
    ];

    $data = [];
    foreach ($fields as $field) {
        if (in_array($field, ['last_company_1_years', 'total_experience_years'])) {
            $data[$field] = !empty($_POST[$field]) ? (int)$_POST[$field] : null;
        } elseif (in_array($field, ['last_company_1_salary', 'previous_salary', 'basic_salary'])) {
            $data[$field] = !empty($_POST[$field]) ? (float)$_POST[$field] : null;
        } else {
            $data[$field] = $_POST[$field] ?? null;
        }
    }

    if ($data['marital_status'] === 'Single') {
        $data['anniversary_date'] = '';
    }

    $required_fields = [
        'id', 'first_name', 'last_name', 'username', 'password', 'role', 'designation', 'division',
        'marital_status', 'gender', 'father_name', 'qualification', 'bank_name', 'account_number',
        'ifsc_code', 'responsibilities', 'level', 'appointment_type', 'location', 'basic_salary',
        'emergency_contact_no', 'emergency_contact_person', 'emergency_contact_relationship'
    ];

    if ($data['marital_status'] !== 'Single') {
        $required_fields[] = 'anniversary_date';
    }

    foreach ($required_fields as $field) {
        if (empty($data[$field]) && $data[$field] !== '0') {
            echo "<div class='alert alert-danger'>Error: $field is required.</div>";
            return;
        }
    }

    $stmt = $conn->prepare("SELECT id, username FROM users WHERE id = ? OR username = ?");
    if (!$stmt) {
        echo "<div class='alert alert-danger'>Database error: Unable to prepare statement.</div>";
        return;
    }
    $stmt->bind_param("ss", $data['id'], $data['username']);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        if ($row['id'] === $data['id']) {
            echo "<div class='alert alert-danger'>Error: ID {$data['id']} already exists.</div>";
            $stmt->close();
            return;
        }
        if ($row['username'] === $data['username']) {
            echo "<div class='alert alert-danger'>Error: Username {$data['username']} already exists.</div>";
            $stmt->close();
            return;
        }
    }
    $stmt->close();

    if ($data['role'] === 'superadmin') {
        echo "<div class='alert alert-danger'>Error: Superadmin role is not allowed.</div>";
        return;
    }

    $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);

    $placeholders = str_repeat('?,', count($fields) - 1) . '?';
    $stmt = $conn->prepare("INSERT INTO users (" . implode(',', $fields) . ") VALUES ($placeholders)");
    if (!$stmt) {
        echo "<div class='alert alert-danger'>Database error: Unable to prepare statement.</div>";
        return;
    }

    $types = str_repeat('s', count($fields));
    $int_fields = ['last_company_1_years', 'total_experience_years'];
    $float_fields = ['last_company_1_salary', 'previous_salary', 'basic_salary'];

    foreach ($int_fields as $f) {
        $i = array_search($f, $fields);
        if ($i !== false) $types = substr_replace($types, 'i', $i, 1);
    }
    foreach ($float_fields as $f) {
        $i = array_search($f, $fields);
        if ($i !== false) $types = substr_replace($types, 'd', $i, 1);
    }

    $stmt->bind_param($types, ...array_values($data));
    if ($stmt->execute()) {
        echo "<div class='alert alert-success'>User created successfully. <a href='manage_users.php'>View Users</a></div>";
    } else {
        echo "<div class='alert alert-danger'>Error: " . htmlspecialchars($stmt->error) . "</div>";
    }
    $stmt->close();
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    createUser($conn);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create User</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
    <style>
        :root {
            --primary-color: #1e3a8a;
            --secondary-color: #22c55e;
            --accent-color: #f97316;
            --sidebar-bg: #1f2937;
            --card-bg: #ffffff;
            --text-color: #111827;
            --hover-bg: #3b82f6;
        }
        body {
            font-family: 'Inter', system-ui, sans-serif;
            background-color: #f3f4f6;
            margin: 0;
            padding: 0;
            display: flex;
            min-height: 100vh;
            color: var(--text-color);
        }
        .sidebar {
            width: 280px;
            background: var(--sidebar-bg);
            color: #fff;
            padding: 20px;
            position: fixed;
            top: 0; bottom: 0;
            z-index: 1000;
            transform: translateX(-280px);
            transition: transform 0.3s ease;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
        }
        .sidebar.active { transform: translateX(0); }
        .sidebar h2 { font-size: 1.5rem; font-weight: 700; margin-bottom: 20px; color: var(--secondary-color); }
        .sidebar a { color: #fff; text-decoration: none; padding: 12px 15px; display: flex; align-items: center; border-radius: 8px; margin-bottom: 8px; font-size: 1rem; transition: background 0.2s; }
        .sidebar a:hover, .sidebar a.active { background: var(--hover-bg); }
        .hamburger { position: fixed; top: 15px; left: 15px; z-index: 1100; background: var(--primary-color); color: #fff; border: none; padding: 10px; border-radius: 8px; cursor: pointer; }
        .hamburger:hover { background: var(--hover-bg); }
        .content { flex: 1; padding: 30px; margin-left: 0; transition: margin-left 0.3s ease; overflow-y: auto; }
        .content.active { margin-left: 280px; }
        h1 { font-size: 2rem; font-weight: 800; margin-bottom: 20px; color: var(--primary-color); text-align: center; }
        .form-container { background: var(--card-bg); padding: 25px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); }
        .required::after { content: '*'; color: red; margin-left: 4px; }
        .disabled-field { background-color: #e5e7eb; cursor: not-allowed; }
        textarea.form-control { min-height: 100px; resize: vertical; }
        .form-control, .form-select { border-radius: 8px; font-size: 0.95rem; }
        .btn-primary { background: var(--primary-color); border: none; border-radius: 8px; padding: 12px; font-size: 1rem; }
        .btn-primary:hover { background: var(--hover-bg); }
        @media (max-width: 576px) {
            .sidebar { width: 240px; transform: translateX(-240px); }
            .content.active { margin-left: 240px; }
            h1 { font-size: 1.5rem; }
            .form-container { padding: 15px; }
        }
    </style>
</head>
<body>
    <button class="hamburger" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>

    <div class="sidebar" id="sidebar">
        <h2>Mypeopleconnect</h2>
        <a class="active" href="<?php echo (strtolower($_SESSION['role']) === 'md') ? 'dashboard_md.php' : 'dashboard_admin.php'; ?>">
            <i class="fas fa-home me-2"></i> <?php echo (strtolower($_SESSION['role']) === 'md') ? 'MD Dashboard' : 'Organisation Chart'; ?>
        </a>
        <a href="logout.php" class="text-danger"><i class="fas fa-sign-out-alt me-2"></i> Logout</a>
    </div>

    <div class="content" id="content">
        <div class="form-container">
            <h1>Create New User</h1>
            <form action="create_user_form.php" method="post">
                <div class="row">

                    <?php
                    $fields = [
                        'id' => 'Employee ID', 'first_name' => 'First Name', 'last_name' => 'Last Name',
                        'username' => 'Username', 'password' => 'Password', 'role' => 'Role', 'email' => 'Email',
                        'mobileno' => 'Mobile No', 'address' => 'Address', 'pancard' => 'PAN Card',
                        'aadharcard' => 'Aadhar Card',
                        'division' => 'division', 'designation' => 'Designation',
                        'marital_status' => 'Marital Status', 'anniversary_date' => 'Anniversary Date',
                        'gender' => 'Gender', 'date_of_birth' => 'Date of Birth', 'date_of_joining' => 'Date of Joining',
                        'father_name' => 'Father\'s Name', 'spouse_name' => 'Spouse Name', 'qualification' => 'Qualification',
                        'previous_experience' => 'Previous Experience', 'company_name' => 'Company Name',
                        'last_company_1' => 'Last Company 1 Name', 'last_company_1_years' => 'Years in Last Company 1',
                        'last_company_1_salary' => 'Salary in Last Company 1', 'total_experience_years' => 'Total Experience (Years)',
                        'previous_salary' => 'Previous Salary', 'uan_no' => 'UAN No', 'bloodgroup' => 'Blood Group',
                        'esic_no' => 'ESIC No', 'bank_name' => 'Bank Name', 'account_number' => 'Account Number',
                        'ifsc_code' => 'IFSC Code', 'responsibilities' => 'Responsibilities', 'level' => 'Level',
                        'appointment_type' => 'Appointment Type', 'location' => 'Location', 'basic_salary' => 'Basic Salary',
                        'kpi' => 'Key Performance Indicators (KPI)',
                        'emergency_contact_no' => 'Emergency Contact No', 'emergency_contact_person' => 'Emergency Contact Person',
                        'emergency_contact_relationship' => 'Relationship with Contact Person'
                    ];

                    $required = ['id','first_name','last_name','username','password','role','division','designation',
                        'marital_status','gender','father_name','qualification','bank_name','account_number',
                        'ifsc_code','responsibilities','level','appointment_type','location','basic_salary',
                        'emergency_contact_no','emergency_contact_person','emergency_contact_relationship'];

                    foreach ($fields as $f => $label) {
                        $is_req = in_array($f, $required);
                        $label_class = $is_req ? 'required' : ($f === 'anniversary_date' ? 'anniversary_label' : '');
                        $req_attr = ($is_req && $f !== 'anniversary_date') ? 'required' : '';

                        if ($f === 'role') {
                            echo "<div class='mb-3 col-md-6'><label class='form-label $label_class'>$label:</label>
                                <select class='form-select' name='$f' $req_attr>
                                    <option value='' disabled selected>Select Role</option>
                                    <option value='admin'>Admin</option>
                                    <option value='admin'>MD</option>
                                    <option value='admin'>CEO</option>
                                    <option value='admin'>CAO</option>
                                    <option value='employee'>Employee</option>
                                    <option value='manager'>Manager</option>
                                </select></div>";

                        } elseif ($f === 'division') {
                            echo "<div class='mb-3 col-md-6'><label class='form-label $label_class'>$label:</label>
                                <select class='form-select' id='division' name='$f' $req_attr onchange='updateDesignations()'>
                                    <option value='' disabled selected>Select division</option>
                                    <option value='HR & ADMIN'>HR & ADMIN</option>
                                    <option value='Finance & Accounts'>Finance & Accounts</option>
                                    <option value='Purchase'>Purchase</option>
                                    <option value='A/C Projects & Services'>A/C Projects & Services</option>
                                    <option value='TAB'>TAB</option>
                                    <option value='Electrical'>Electrical</option>
                                </select></div>";

                        } elseif ($f === 'designation') {
                            echo "<div class='mb-3 col-md-6'><label class='form-label $label_class'>$label:</label>
                                <select class='form-select' id='designation' name='$f' $req_attr>
                                    <option value='' disabled selected>Select Designation</option>
                                </select></div>";

                        } elseif ($f === 'marital_status') {
                            echo "<div class='mb-3 col-md-6'><label class='form-label $label_class'>$label:</label>
                                <select class='form-select' id='$f' name='$f' $req_attr onchange='toggleAnniversaryDate()'>
                                    <option value='' disabled selected>Select Marital Status</option>
                                    <option value='Single'>Single</option>
                                    <option value='Married'>Married</option>
                                    <option value='Divorced'>Divorced</option>
                                </select></div>";

                        } elseif ($f === 'anniversary_date') {
                            echo "<div class='mb-3 col-md-6'><label class='form-label $label_class' id='anniversary_label'>$label:</label>
                                <input type='text' id='$f' class='form-control datepicker' name='$f'></div>";

                        } elseif ($f === 'gender') {
                            echo "<div class='mb-3 col-md-6'><label class='form-label $label_class'>$label:</label>
                                <select class='form-select' name='$f' $req_attr>
                                    <option value='' disabled selected>Select Gender</option>
                                    <option value='Male'>Male</option>
                                    <option value='Female'>Female</option>
                                    <option value='Others'>Others</option>
                                </select></div>";

                        } elseif ($f === 'level') {
                            echo "<div class='mb-3 col-md-6'><label class='form-label $label_class'>$label:</label>
                                <select class='form-select' name='$f' $req_attr>
                                    <option value='' disabled selected>Select Level</option>
                                    <option value='L1'>L1</option><option value='L2'>L2</option><option value='L3'>L3</option>
                                    <option value='L4'>L4</option><option value='L5'>L5</option>
                                </select></div>";

                        } elseif ($f === 'appointment_type') {
                            echo "<div class='mb-3 col-md-6'><label class='form-label $label_class'>$label:</label>
                                <select class='form-select' name='$f' $req_attr>
                                    <option value='' disabled selected>Select Type</option>
                                    <option value='regular'>Regular</option>
                                    <option value='contract'>Contract</option>
                                </select></div>";

                        } elseif ($f === 'location') {
                            echo "<div class='mb-3 col-md-6'><label class='form-label $label_class'>$label:</label>
                                <select class='form-select' name='$f' $req_attr>
                                    <option value='' disabled selected>Select Location</option>
                                    <option value='chennai'>Chennai</option>
                                    <option value='coimbatore'>Coimbatore</option>
                                    <option value='madurai'>Madurai</option>
                                    <option value='bengaluru'>Bengaluru</option>
                                </select></div>";

                        } elseif (in_array($f, ['last_company_1_years', 'total_experience_years'])) {
                            echo "<div class='mb-3 col-md-6'><label class='form-label'>$label:</label>
                                <input type='number' class='form-control' name='$f' min='0'></div>";

                        } elseif (in_array($f, ['last_company_1_salary', 'previous_salary', 'basic_salary'])) {
                            echo "<div class='mb-3 col-md-6'><label class='form-label'>$label:</label>
                                <input type='number' class='form-control' name='$f' step='0.01' min='0'></div>";

                        } elseif ($f === 'kpi') {
                            echo "<div class='mb-3 col-md-6'><label class='form-label'>$label:</label>
                                <textarea class='form-control' name='$f' placeholder='Enter KPIs'></textarea></div>";

                        } else {
                            $type = ($f === 'password') ? 'password' : 'text';
                            $class = in_array($f, ['date_of_birth','date_of_joining','anniversary_date']) ? 'datepicker' : '';
                            echo "<div class='mb-3 col-md-6'><label class='form-label $label_class'>$label:</label>
                                <input type='$type' class='form-control $class' name='$f' $req_attr></div>";
                        }
                    }
                    ?>
                </div>
                <button type="submit" class="btn btn-primary w-100">Create User</button>
            </form>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('active');
            document.getElementById('content').classList.toggle('active');
        }

        function toggleAnniversaryDate() {
            const status = document.getElementById('marital_status').value;
            const input = document.getElementById('anniversary_date');
            const label = document.getElementById('anniversary_label');
            if (status === 'Single') {
                input.disabled = true; input.classList.add('disabled-field'); input.value = '';
                label.classList.remove('required');
            } else {
                input.disabled = false; input.classList.remove('disabled-field');
                label.classList.add('required');
            }
        }

        const designations = {
            'HR & ADMIN': [
                'HR-MANAGER',
                'HR-EXECUTIVE'
            ],
            'Finance & Accounts': [
                'FINANCE-SENIOR MANAGER',
                'FINANCE-MANAGER',
                'FINANCE-ASST. MANAGER',
                'ACCOUNTS-EXECUTIVE',
                'ACCOUNTS- JUNIOR EXECUTIVE'
            ],
            'Purchase': [
                'PURCHASE-SENIOR MANAGER',
                'PURCHASE-MANAGER',
                'PURCHASE-ASST. MANAGER',
                'PURCHASE-EXECUTIVE'
            ],
            'A/C Projects & Services': [
                'A/C PROJECTS & SERVICES - PROJECT MANAGER',
                'A/C PROJECTS & SERVICES - ASST. PROJECT MANAGER',
                'A/C PROJECTS & SERVICES - SERVICE ENGINEER',
                'A/C PROJECTS & SERVICES - SERVICE EXECUTIVE',
                'A/C PROJECTS & SERVICES - SENIOR PROJECT MANAGER',
                'A/C PROJECTS & SERVICES - SENIOR TECHNICIAN',
                'A/C PROJECTS & SERVICES - PROJECT ENGINEER',
                'A/C PROJECTS & SERVICES - PLANNING ENGINEER',
                'A/C PROJECTS & SERVICES - TECHNICIAN',
                'A/C PROJECTS & SERVICES - JUNIOR TECHNICIAN'
            ],
            'TAB': [
                'TAB-OPERATION MANAGER',
                'TAB-BUSINESS DEVELOPMENT EXECUTIVE(BDE)',
                'TAB-TEAM LEADER',
                'TAB-PROJECT ENGINEER',
                'TAB-SERVICE ENGINEER',
                'TAB-TECHNICIAN'
            ],
            'Electrical': [
                'ELECTRICAL-OPERATION HEAD',
                'ELECTRICAL-BUSINESS DEVELOPMENT EXECUTIVE(BDE)',
                'ELECTRICAL-PRODUCTION SUPERVISOR'
            ]
        };

        function updateDesignations() {
            const dept = document.getElementById('division').value;
            const select = document.getElementById('designation');
            select.innerHTML = '<option value="" disabled selected>Select Designation</option>';
            if (dept && designations[dept]) {
                designations[dept].forEach(d => {
                    const option = document.createElement('option');
                    option.value = d;
                    option.textContent = d;
                    select.appendChild(option);
                });
            }
        }

        $(document).ready(function() {
            $(".datepicker").datepicker({
                dateFormat: "yy-mm-dd",
                changeMonth: true,
                changeYear: true,
                yearRange: "1900:2100"
            });
            toggleAnniversaryDate();
        });
    </script>
</body>
</html>