<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

require_login();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../dashboard/cds_groups.php');
    exit;
}

$groupId = $_POST['group_id'] ?? 0;
$corpsMemberId = $_POST['corps_member_id'] ?? 0;

if (empty($groupId) || empty($corpsMemberId)) {
    $_SESSION['error'] = "Invalid request.";
    header("Location: ../dashboard/cds_group_members.php?id={$groupId}");
    exit;
}

/*
|--------------------------------------------------------------------------
| Prevent duplicate assignment
|--------------------------------------------------------------------------
*/
$checkStmt = $db->prepare("
    SELECT id
    FROM cds_group_members
    WHERE cds_group_id = ?
    AND corps_member_id = ?
");

$checkStmt->execute([
    $groupId,
    $corpsMemberId
]);

if ($checkStmt->fetch()) {
    $_SESSION['error'] = "Member already belongs to this CDS group.";
    header("Location: ../dashboard/cds_group_members.php?id={$groupId}");
    exit;
}

/*
|--------------------------------------------------------------------------
| Add member
|--------------------------------------------------------------------------
*/
$stmt = $db->prepare("
    INSERT INTO cds_group_members
    (
        cds_group_id,
        corps_member_id,
        assigned_date,
        is_executive,
        executive_position,
        status
    )
    VALUES
    (
        ?, ?, ?, ?, ?, ?
    )
");

$stmt->execute([
    $groupId,
    $corpsMemberId,
    date('Y-m-d'),
    'No',
    null,
    'Active'
]);

$_SESSION['success'] = "Member added successfully.";

header("Location: ../dashboard/cds_group_members.php?id={$groupId}");
exit;