<?php

require_once '../includes/auth.php';

require_login();

if($_SERVER['REQUEST_METHOD'] != 'POST'){
    exit;
}

$db->beginTransaction();

try{

    $stmt = $db->prepare("
        INSERT INTO cds_groups(
            group_name,
            group_code,
            meeting_day,
            meeting_time,
            meeting_venue,
            description
        )
        VALUES(
            ?,
            ?,
            ?,
            ?,
            ?,
            ?
        )
    ");

    $stmt->execute([
        $_POST['group_name'],
        $_POST['group_code'],
        $_POST['meeting_day'],
        $_POST['meeting_time'],
        $_POST['meeting_venue'],
        $_POST['description']
    ]);

    $groupId = $db->lastInsertId();

    if(!empty($_POST['members'])){

        foreach($_POST['members'] as $member){

            $stmt = $db->prepare("
                INSERT INTO cds_group_members(
                    cds_group_id,
                    corps_member_id,
                    assigned_date
                )
                VALUES(
                    ?,
                    ?,
                    CURDATE()
                )
            ");

            $stmt->execute([
                $groupId,
                $member
            ]);
        }
    }

    $db->commit();

}catch(Exception $e){

    $db->rollBack();

    die($e->getMessage());
}

header("Location: ../dashboard/cds_groups.php");
exit;