<?php
// add_user.php

include('include/dbcon.php');

// ---------- Helper: generate next member ID (MC0001, MC0002, ...) ----------
function generateNextMemberId($con) {
    $prefix = 'MC';
    $padLength = 4; // MC + 4 digits

    // Find last ID that starts with MC
    $sql = "SELECT school_number 
            FROM user 
            WHERE school_number LIKE 'MC%' 
            ORDER BY school_number DESC 
            LIMIT 1";

    $res = mysqli_query($con, $sql);
    if ($res && mysqli_num_rows($res) > 0) {
        $row = mysqli_fetch_assoc($res);
        $lastId = $row['school_number'];    // e.g., MC0025
        // Get numeric part after prefix
        $numPart = (int)substr($lastId, strlen($prefix));
        $nextNum = $numPart + 1;
    } else {
        // If no MC-based ID exists yet, start at 1
        $nextNum = 1;
    }

    // Build new ID, e.g., MC0001
    return $prefix . str_pad($nextNum, $padLength, '0', STR_PAD_LEFT);
}

// Generate next ID for display and insert
$next_school_number = generateNextMemberId($con);

// ---------- Handle form submit ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {

    // We IGNORE any posted school_number and always use generated one
    $school_number = $next_school_number;

    $firstname  = $_POST['firstname']  ?? '';
    $middlename = $_POST['middlename'] ?? '';
    $lastname   = $_POST['lastname']   ?? '';
    $contact    = $_POST['contact']    ?? '';
    $gender     = $_POST['gender']     ?? '';
    $address    = $_POST['address']    ?? '';
    $type       = $_POST['type']       ?? '';
    $level      = $_POST['level']      ?? '';
    $section    = $_POST['section']    ?? '';

    // Check duplicate (very unlikely with auto IDs, but kept for safety)
    $safe_school = mysqli_real_escape_string($con, $school_number);
    $result = mysqli_query($con, "SELECT * FROM user WHERE school_number = '$safe_school'") or die(mysqli_error($con));
    $row    = mysqli_num_rows($result);

    if ($row > 0) {
        echo "<script>alert('Generated ID already exists! Please try again.'); window.location='user.php'</script>";
        exit;
    } else {
        // Insert new user
        $sql = "INSERT INTO user (
                    school_number,
                    firstname,
                    middlename,
                    lastname,
                    contact,
                    gender,
                    address,
                    type,
                    level,
                    section,
                    status,
                    user_added
                ) VALUES (
                    '" . mysqli_real_escape_string($con, $school_number) . "',
                    '" . mysqli_real_escape_string($con, $firstname) . "',
                    '" . mysqli_real_escape_string($con, $middlename) . "',
                    '" . mysqli_real_escape_string($con, $lastname) . "',
                    '" . mysqli_real_escape_string($con, $contact) . "',
                    '" . mysqli_real_escape_string($con, $gender) . "',
                    '" . mysqli_real_escape_string($con, $address) . "',
                    '" . mysqli_real_escape_string($con, $type) . "',
                    '" . mysqli_real_escape_string($con, $level) . "',
                    '" . mysqli_real_escape_string($con, $section) . "',
                    'Active',
                    NOW()
                )";

        if (!mysqli_query($con, $sql)) {
            die("Error saving user: " . mysqli_error($con));
        }

        // On success: go to member barcode page (ID card / sticker)
        header('Location: view_member_barcode.php?school_number=' . urlencode($school_number));
        exit;
    }
}
?>

<?php include ('header.php'); ?>

<div class="page-title">
    <div class="title_left">
        <h3>
            <small>Home / Members</small>
        </h3>
    </div>
</div>
<div class="clearfix"></div>

<div class="row">
    <div class="col-md-12 col-sm-12 col-xs-12">
        <div class="x_panel">
            <div class="x_title">
                <ul class="nav navbar-right panel_toolbox">
                    <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a></li>
                    <li><a class="close-link"><i class="fa fa-close"></i></a></li>
                </ul>
                <div class="clearfix"></div>
            </div>
            <div class="x_content">
                <!-- content starts here -->

                <form method="post" enctype="multipart/form-data" class="form-horizontal form-label-left">

                    <!-- AUTO-GENERATED ID (READONLY) -->
                    <div class="form-group">
                        <label class="control-label col-md-4" for="school-number">
                            ID Number <span class="required" style="color:red;">*</span>
                        </label>
                        <div class="col-md-3">
                            <input type="text"
                                   name="school_number_display"
                                   id="school-number"
                                   class="form-control col-md-7 col-xs-12"
                                   value="<?php echo htmlspecialchars($next_school_number); ?>"
                                   readonly>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label col-md-4" for="first-name">First Name <span class="required" style="color:red;">*</span>
                        </label>
                        <div class="col-md-3">
                            <input type="text" name="firstname" placeholder="First Name....." id="first-name2" required="required" class="form-control col-md-7 col-xs-12">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label col-md-4" for="first-name">Middle Name
                        </label>
                        <div class="col-md-3">
                            <input type="text" name="middlename" placeholder="MI / Middle Name....." id="first-name2" class="form-control col-md-7 col-xs-12">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label col-md-4" for="last-name">Last Name <span class="required" style="color:red;">*</span>
                        </label>
                        <div class="col-md-3">
                            <input type="text" name="lastname" placeholder="Last Name....." id="last-name2" required="required" class="form-control col-md-7 col-xs-12">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label col-md-4" for="last-name">Contact
                        </label>
                        <div class="col-md-3">
                            <input type="tel" pattern="[0-9]{11,11}" autocomplete="off" maxlength="11" name="contact" id="last-name2" class="form-control col-md-7 col-xs-12">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label col-md-4" for="last-name">Gender <span class="required" style="color:red;">*</span>
                        </label>
                        <div class="col-md-4">
                            <select name="gender" class="select2_single form-control" required="required" tabindex="-1" >
                                <option value="Male">Male</option>
                                <option value="Female">Female</option>
                            </select>
                        </div>
                    </div>								

                    <div class="form-group">
                        <label class="control-label col-md-4" for="last-name">Address
                        </label>
                        <div class="col-md-4">
                            <input type="text" name="address" id="last-name2" class="form-control col-md-7 col-xs-12">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label col-md-4" for="last-name">Type <span class="required" style="color:red;">*</span>
                        </label>
                        <div class="col-md-4">
                            <select name="type" class="select2_single form-control" required="required" tabindex="-1" >
                                <option value="Student">Student</option>
                                <option value="Teacher">Teacher</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label col-md-4" for="last-name">Level <span class="required" style="color:red;">*</span>
                        </label>
                        <div class="col-md-4">
                            <select name="level" class="select2_single form-control" required="required" tabindex="-1" >
                                <option value="Grade 7">Grade 7</option>
                                <option value="Grade 8">Grade 8</option>
                                <option value="Grade 9">Grade 9</option>
                                <option value="Grade 10">Grade 10</option>
                                <option value="Faculty">Faculty</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label col-md-4" for="first-name">Section <span class="required" style="color:red;">*</span>
                        </label>
                        <div class="col-md-3">
                            <input type="text" name="section" placeholder="Section....." id="first-name2" required="required" class="form-control col-md-7 col-xs-12">
                        </div>
                    </div>

                    <div class="ln_solid"></div>
                    <div class="form-group">
                        <div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
                            <a href="user.php">
                                <button type="button" class="btn btn-primary">
                                    <i class="fa fa-times-circle-o"></i> Cancel
                                </button>
                            </a>
                            <button type="submit" name="submit" class="btn btn-success">
                                <i class="fa fa-plus-square"></i> Submit
                            </button>
                        </div>
                    </div>
                </form>

                <!-- content ends here -->
            </div>
        </div>
    </div>
</div>

<?php include ('footer.php'); ?>
