<?php
/**
 * modules/rates/add_rates.php
 */

$p = $GLOBALS['my_privs'] ?? ['can_add' => 0];
if (in_array(1, $_SESSION['all_role_ids'] ?? [])) { $p['can_add'] = 1; }

if ($p['can_add'] == 0) {
    header("Location: index.php?s=" . encrypt_url('mod=rates&page=list_rates') . "&status=access_denied");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $category_id = (int)$_POST['category_id'];
    $type_id     = (int)$_POST['type_id'];
    $rate        = (float)$_POST['rate_per_ton'];
    $eff_from    = $db->escape($_POST['effective_from']);
    $created_by  = (int)$_SESSION['user_id'];

    // ERP MAGIC: Close the old active rate for this specific Category + Type
    // Set its end date to 1 day before this new rate starts, and mark it HISTORICAL
    $close_old_sql = "UPDATE TBL_RATES 
                      SET EFFECTIVE_TO = DATE_SUB('$eff_from', INTERVAL 1 DAY),
                          STATUS = 'HISTORICAL',
                          UPDATED_BY = $created_by,
                          UPDATED_DATE = CURRENT_TIMESTAMP
                      WHERE CATEGORY_ID = $category_id 
                        AND TYPE_ID = $type_id 
                        AND STATUS = 'ACTIVE' 
                        AND EFFECTIVE_TO IS NULL";
    $db->query($close_old_sql);

    // Now insert the brand new active rate
    $sql = "INSERT INTO TBL_RATES (CATEGORY_ID, TYPE_ID, RATE_PER_TON, EFFECTIVE_FROM, STATUS, CREATED_BY) 
            VALUES ($category_id, $type_id, $rate, '$eff_from', 'ACTIVE', $created_by)";
    
    if ($db->query($sql)) {
        header("Location: index.php?s=" . encrypt_url('mod=rates&page=list_rates') . "&status=added");
        exit;
    }
}

// Fetch Dropdowns
$cat_sql = "SELECT CATEGORY_ID, CATEGORY_NAME FROM TBL_CATEGORIES WHERE STATUS = 'ACTIVE' ORDER BY CATEGORY_NAME ASC";
$cat_res = $db->query($cat_sql);

$type_sql = "SELECT TYPE_ID, TYPE_NAME FROM TBL_COAL_TYPES WHERE STATUS = 'ACTIVE' ORDER BY TYPE_NAME ASC";
$type_res = $db->query($type_sql);
?>

<div class="p-3">
    <section class="content-header px-0">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="font-weight-bold text-primary"><i class="fas fa-plus-circle mr-2"></i>Register New Rate</h1>
                </div>
                <div class="col-sm-6 text-right">
                    <a href="index.php?s=<?php echo encrypt_url('mod=rates&page=list_rates'); ?>" class="btn btn-default shadow-sm border">
                        <i class="fas fa-arrow-left mr-1"></i> Back to List
                    </a>
                </div>
            </div>
        </div>
    </section>

    <section class="content px-0">
        <div class="container-fluid">
            <form action="" method="POST">
                <div class="card card-outline card-primary shadow-sm" style="border-top: 4px solid #007bff;">
                    <div class="card-body">
                        
                        <div class="alert alert-info border-0 shadow-sm" style="background-color: #e8f4fd;">
                            <i class="fas fa-info-circle mr-2"></i> <strong>ERP Automation Notice:</strong> If an active rate already exists for the selected Category & Type, saving this form will automatically archive the old rate and set its end date to preserve historical dispatch data.
                        </div>

                        <div class="row mt-4">
                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Coal Category <span class="text-danger">*</span></label>
                                <select name="category_id" class="form-control" required>
                                    <option value="">-- Select Category --</option>
                                    <?php while($c = mysqli_fetch_assoc($cat_res)): ?>
                                        <option value="<?php echo $c['CATEGORY_ID']; ?>"><?php echo htmlspecialchars($c['CATEGORY_NAME']); ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>

                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Coal Type <span class="text-danger">*</span></label>
                                <select name="type_id" class="form-control" required>
                                    <option value="">-- Select Type --</option>
                                    <?php while($t = mysqli_fetch_assoc($type_res)): ?>
                                        <option value="<?php echo $t['TYPE_ID']; ?>"><?php echo htmlspecialchars($t['TYPE_NAME']); ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Rate Per Ton (Rs) <span class="text-danger">*</span></label>
                                <input type="number" step="0.01" min="0" name="rate_per_ton" class="form-control font-weight-bold text-success" placeholder="0.00" required>
                            </div>

                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Effective From Date <span class="text-danger">*</span></label>
                                <input type="date" name="effective_from" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                        </div>
                    </div>
                    <div class="card-footer bg-white text-right p-3">
                        <button type="submit" class="btn btn-primary px-5 font-weight-bold shadow-sm">
                            <i class="fas fa-save mr-2"></i> PUBLISH NEW RATE
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </section>
</div>