<?php

require_once __DIR__ . '/../library/auth.php';

allow_roles(['admin']);

$school_id =
    $_SESSION['school_id'];

/*
|--------------------------------------------------------------------------
| CHECK IMPORT SESSION
|--------------------------------------------------------------------------
*/

if (

    !isset($_SESSION['student_import_headers']) ||

    !isset($_SESSION['student_import_data'])

) {

    $_SESSION['error_message'] =
        'No import data found.';

    header('Location: import_students.php');

    exit;
}

/*
|--------------------------------------------------------------------------
| IMPORT DATA
|--------------------------------------------------------------------------
*/

$headers =
    $_SESSION['student_import_headers'];

$excel_data =
    $_SESSION['student_import_data'];

/*
|--------------------------------------------------------------------------
| DUPLICATE HEADER CHECK
|--------------------------------------------------------------------------
*/

$duplicate_headers = array_diff_assoc(

    $headers,
    array_unique($headers)

);

if (!empty($duplicate_headers)) {

    $_SESSION['error_message'] =

        'Duplicate column names found in excel file.';

    header('Location: import_students.php');

    exit;
}

/*
|--------------------------------------------------------------------------
| EMPTY HEADER VALIDATION
|--------------------------------------------------------------------------
*/

foreach ($headers as $header) {

    if (trim($header) === '') {

        $_SESSION['error_message'] =
            'Blank column header found in excel file.';

        header('Location: import_students.php');

        exit;

    }

}

/*
|--------------------------------------------------------------------------
| VALIDATION
|--------------------------------------------------------------------------
*/

$validation_errors = [];

foreach (

    $excel_data
    as $row_index => $row

) {

    $row_errors = [];

    /*
    |--------------------------------------------------------------------------
    | STUDENT NAME VALIDATION
    |--------------------------------------------------------------------------
    */

    $student_name = trim(

        $row['First Name']
        ?? ''

    );

    if ($student_name === '') {

        $row_errors[] =
            'First Name missing';

    }

    /*
    |--------------------------------------------------------------------------
    | CLASS VALIDATION
    |--------------------------------------------------------------------------
    */

    $class_name = trim(

        $row['Class']
        ?? ''

    );

    $class_data = null;

    if ($class_name === '') {

        $row_errors[] =
            'Class missing';

    } else {

        $classStmt = $pdo->prepare("

            SELECT id

            FROM classes

            WHERE class_name = ?
            AND school_id = ?

            LIMIT 1

        ");

        $classStmt->execute([

            $class_name,
            $school_id

        ]);

        $class_data =
            $classStmt->fetch(
                PDO::FETCH_ASSOC
            );

        if (!$class_data) {

            $row_errors[] =
                'Invalid class';

        }

    }

    /*
    |--------------------------------------------------------------------------
    | DUPLICATE ROLL VALIDATION
    |--------------------------------------------------------------------------
    */

    $roll_no = trim(

        $row['Roll No']
        ?? ''

    );

    if (

        $roll_no !== '' &&
        !empty($class_data)

    ) {

        $rollStmt = $pdo->prepare("

            SELECT id

            FROM student_sessions

            WHERE school_id = ?
            AND class_id = ?
            AND roll_no = ?

            LIMIT 1

        ");

        $rollStmt->execute([

            $school_id,
            $class_data['id'],
            $roll_no

        ]);

        if ($rollStmt->fetch()) {

            $row_errors[] =
                'Duplicate roll number in same class';

        }

    }

    /*
    |--------------------------------------------------------------------------
    | STORE ERRORS
    |--------------------------------------------------------------------------
    */

    if (!empty($row_errors)) {

        $validation_errors[$row_index] =
            $row_errors;

    }

}

/*
|--------------------------------------------------------------------------
| FIELD MAPPING
|--------------------------------------------------------------------------
*/

$student_fields = [

    // STUDENTS

    'first_name'     => 'First Name',
    'last_name'      => 'Last Name',
    'name'           => 'Full Name',

    'gender'         => 'Gender',
    'dob'            => 'DOB',

    'phone'          => 'Phone',
    'email'          => 'Email',

    'admission_date' => 'Admission Date',
    'admission_no'   => 'Admission No',
    'enrollment_no'  => 'Scholar No',

    // SESSION

    'class_id'       => 'Class',
    'section'        => 'Section',
    'roll_no'        => 'Roll No',

    // PARENTS

    'father_name'    => 'Father Name',
    'father_phone'   => 'Father Phone',

    'mother_name'    => 'Mother Name',

    // ADDRESS

    'address'        => 'Address',

    // DOCUMENTS

    'aadhaar_no'     => 'Aadhaar No'

];

$page_title =
    'Preview Student Import';

require_once __DIR__ . '/../include/header.php';
require_once __DIR__ . '/../include/sidebar.php';

?>

<div class="content-wrapper">

    <!-- PAGE HEADER -->

    <section class="content-header">

        <div class="container-fluid">

            <div
                class="
                    row
                    mb-2
                    align-items-center
                "
            >

                <div class="col-sm-6">

                    <h1>

                        Preview Student Import

                    </h1>

                </div>

            </div>

        </div>

    </section>

    <!-- MAIN CONTENT -->

    <section class="content">

        <div class="container-fluid">

            <div
                class="
                    card
                    card-primary
                    card-outline
                "
            >

                <!-- CARD HEADER -->

                <div class="card-header">

                    <h3 class="card-title">

                        Column Mapping

                    </h3>

                </div>

                <!-- FORM -->

                <form
                    action="confirm_student_import.php"
                    method="POST"
                >

                    <div class="card-body">

                        <!-- FIELD MAPPING TABLE -->

                        <div class="table-responsive">

                            <table
                                class="
                                    table
                                    table-bordered
                                    table-striped
                                "
                            >

                                <thead
                                    class="
                                        thead-dark
                                    "
                                >

                                    <tr>

                                        <th
                                            style="
                                                width:50%;
                                            "
                                        >

                                            Excel Column

                                        </th>

                                        <th
                                            style="
                                                width:50%;
                                            "
                                        >

                                            Database Field

                                        </th>

                                    </tr>

                                </thead>

                                <tbody>

                                    <?php foreach (
                                        $headers
                                        as $header
                                    ) { ?>

                                        <tr>

                                            <!-- HEADER -->

                                            <td>

                                                <strong>

                                                    <?= htmlspecialchars(
                                                        $header
                                                    ) ?>

                                                </strong>

                                            </td>

                                            <!-- FIELD -->

                                            <td>

                                                <select
                                                    name="field_mapping[<?= htmlspecialchars($header) ?>]"

                                                    class="form-control"
                                                >

                                                    <option value="">

                                                        -- Skip Column --

                                                    </option>

                                                    <?php foreach (

                                                        $student_fields
                                                        as $field_key => $field_label

                                                    ) {

                                                        $selected = '';

                                                        if (

                                                            strtolower(
                                                                trim($header)
                                                            )

                                                            ===

                                                            strtolower(
                                                                trim($field_label)
                                                            )

                                                        ) {

                                                            $selected =
                                                                'selected';

                                                        }

                                                    ?>

                                                        <option
                                                            value="<?= htmlspecialchars($field_key) ?>"

                                                            <?= $selected ?>
                                                        >

                                                            <?= htmlspecialchars($field_label) ?>

                                                        </option>

                                                    <?php } ?>

                                                </select>

                                            </td>

                                        </tr>

                                    <?php } ?>

                                </tbody>

                            </table>

                        </div>

                        <hr>

                        <h4>

                            Excel Preview

                        </h4>

                        <p class="text-muted">

                            Showing first 10 rows out of

                            <?= count($excel_data) ?>

                            rows.

                        </p>
						                        <!-- PREVIEW TABLE -->

                        <div class="table-responsive">

                            <table
                                class="
                                    table
                                    table-bordered
                                    table-striped
                                    table-hover
                                    table-sm
                                "
                            >

                                <thead
                                    class="
                                        thead-dark
                                    "
                                >

                                    <tr>

                                        <?php foreach (
                                            $headers
                                            as $header
                                        ) { ?>

                                            <th>

                                                <?= htmlspecialchars(
                                                    $header
                                                ) ?>

                                            </th>

                                        <?php } ?>

                                        <th>

                                            Status

                                        </th>

                                        <th>

                                            Validation Errors

                                        </th>

                                    </tr>

                                </thead>

                                <tbody>

                                    <?php

                                    $preview_rows =
                                        array_slice(
                                            $excel_data,
                                            0,
                                            10
                                        );

                                    ?>

                                    <?php foreach (

                                        $preview_rows
                                        as $row_index => $row

                                    ) { ?>

                                        <?php

                                        $has_errors =
                                            isset(
                                                $validation_errors[$row_index]
                                            );

                                        ?>

                                        <tr
                                            class="<?= $has_errors
                                                ? 'table-danger'
                                                : '' ?>"
                                        >

                                            <!-- EXCEL DATA -->

                                            <?php foreach (

                                                $headers
                                                as $header

                                            ) { ?>

                                                <td>

                                                    <?= htmlspecialchars(

                                                        $row[$header]
                                                        ?? ''

                                                    ) ?>

                                                </td>

                                            <?php } ?>

                                            <!-- STATUS -->

                                            <td
                                                class="
                                                    align-middle
                                                    text-center
                                                "
                                            >

                                                <?php if (
                                                    $has_errors
                                                ) { ?>

                                                    <span
                                                        class="
                                                            badge
                                                            badge-danger
                                                            px-3
                                                            py-2
                                                        "
                                                    >

                                                        Invalid

                                                    </span>

                                                <?php } else { ?>

                                                    <span
                                                        class="
                                                            badge
                                                            badge-success
                                                            px-3
                                                            py-2
                                                        "
                                                    >

                                                        Valid

                                                    </span>

                                                <?php } ?>

                                            </td>

                                            <!-- ERRORS -->

                                            <td
                                                class="
                                                    align-middle
                                                "
                                            >

                                                <?php if (
                                                    $has_errors
                                                ) { ?>

                                                    <ul
                                                        class="
                                                            mb-0
                                                            pl-3
                                                            text-danger
                                                        "
                                                    >

                                                        <?php foreach (

                                                            $validation_errors[$row_index]
                                                            as $error

                                                        ) { ?>

                                                            <li>

                                                                <?= htmlspecialchars(
                                                                    $error
                                                                ) ?>

                                                            </li>

                                                        <?php } ?>

                                                    </ul>

                                                <?php } else { ?>

                                                    <span
                                                        class="
                                                            text-success
                                                        "
                                                    >

                                                        No Errors

                                                    </span>

                                                <?php } ?>

                                            </td>

                                        </tr>

                                    <?php } ?>

                                </tbody>

                            </table>

                        </div>

                    </div>

                    <!-- CARD FOOTER -->

                    <div class="card-footer">

                        <div
                            class="
                                row
                                align-items-center
                            "
                        >

                            <!-- LEFT -->

                            <div
                                class="
                                    col-lg-6
                                    col-md-12
                                    mb-2
                                    mb-lg-0
                                "
                            >

                                <?php if (
                                    !empty($validation_errors)
                                ) { ?>

                                    <div
                                        class="
                                            text-danger
                                        "
                                    >

                                        <i
                                            class="
                                                fas
                                                fa-exclamation-triangle
                                                mr-1
                                            "
                                        ></i>

                                        Please fix validation
                                        errors before import.

                                    </div>

                                <?php } else { ?>

                                    <div
                                        class="
                                            text-success
                                        "
                                    >

                                        <i
                                            class="
                                                fas
                                                fa-check-circle
                                                mr-1
                                            "
                                        ></i>

                                        Validation completed successfully.

                                    </div>

                                <?php } ?>

                            </div>

                            <!-- RIGHT -->

                            <div
                                class="
                                    col-lg-6
                                    col-md-12
                                    text-lg-right
                                "
                            >

                                <a
                                    href="import_students.php"

                                    class="
                                        btn
                                        btn-secondary
                                        mb-2
                                    "
                                >

                                    <i
                                        class="
                                            fas
                                            fa-times
                                            mr-1
                                        "
                                    ></i>

                                    Cancel

                                </a>

                                <button

                                    type="submit"

                                    class="
                                        btn
                                        btn-success
                                        mb-2
                                    "

                                    <?= !empty($validation_errors)
                                        ? 'disabled'
                                        : '' ?>

                                >

                                    <i
                                        class="
                                            fas
                                            fa-check
                                            mr-1
                                        "
                                    ></i>

                                    Confirm Import

                                </button>

                            </div>

                        </div>

                    </div>

                </form>

            </div>

        </div>

    </section>

</div>

<?php require_once __DIR__ . '/../include/footer.php'; ?>