<?php
/**
 * Delete Remedy
 * Remove a remedy from the system with safety checks
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';

requireAdmin();

$pdo = getDB();
$remedyId = (int)($_GET['id'] ?? 0);
$error = '';
$success = '';

// Get remedy details
$stmt = $pdo->prepare("SELECT * FROM remedies WHERE id = ?");
$stmt->execute([$remedyId]);
$remedy = $stmt->fetch();

if (!$remedy) {
    header('Location: index.php?error=Remedy not found');
    exit;
}

// Check dependencies
$stmt = $pdo->prepare("SELECT COUNT(*) as count FROM rubric_remedy WHERE remedy_id = ?");
$stmt->execute([$remedyId]);
$rubricCount = $stmt->fetch()['count'];

$stmt = $pdo->prepare("SELECT COUNT(*) as count FROM cases WHERE prescribed_remedy_id = ?");
$stmt->execute([$remedyId]);
$prescriptionCount = $stmt->fetch()['count'];

// Handle deletion
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $confirm = $_POST['confirm'] ?? '';
    
    if ($confirm == 'DELETE') {
        if ($prescriptionCount > 0) {
            $error = "Cannot delete remedy that has been used in prescriptions. ($prescriptionCount prescriptions found)";
        } else {
            beginTransaction();
            try {
                // Delete from rubric_remedy first
                $stmt = $pdo->prepare("DELETE FROM rubric_remedy WHERE remedy_id = ?");
                $stmt->execute([$remedyId]);
                
                // Delete the remedy
                $stmt = $pdo->prepare("DELETE FROM remedies WHERE id = ?");
                $stmt->execute([$remedyId]);
                
                commitTransaction();
                $success = "Remedy deleted successfully!";
                header("refresh:2;url=index.php");
            } catch (Exception $e) {
                rollbackTransaction();
                $error = "Failed to delete: " . $e->getMessage();
            }
        }
    } else {
        $error = "Please type DELETE to confirm deletion";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Delete Remedy - Admin Panel</title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-6 mx-auto">
                <div class="card">
                    <div class="card-header bg-danger text-white">
                        <h4 class="mb-0"><i class="fas fa-exclamation-triangle"></i> Delete Remedy</h4>
                    </div>
                    <div class="card-body">
                        <?php if ($error): ?>
                            <div class="alert alert-danger"><?php echo $error; ?></div>
                        <?php endif; ?>
                        
                        <?php if ($success): ?>
                            <div class="alert alert-success"><?php echo $success; ?></div>
                        <?php else: ?>
                            <div class="alert alert-warning">
                                <strong>⚠️ Warning!</strong><br>
                                You are about to delete the following remedy:
                            </div>
                            
                            <table class="table table-bordered">
                                <tr><th>Remedy Name:</th><td><strong><?php echo escape($remedy['name']); ?></strong></td></tr>
                                <?php if ($remedy['abbreviation']): ?>
                                <tr><th>Abbreviation:</th><td><?php echo escape($remedy['abbreviation']); ?></td></tr>
                                <?php endif; ?>
                                <tr><th>Rubric Links:</th><td><?php echo $rubricCount; ?> rubric(s)</td></tr>
                                <tr><th>Prescriptions:</th><td><?php echo $prescriptionCount; ?> prescription(s)</td></tr>
                            </table>
                            
                            <?php if ($prescriptionCount > 0): ?>
                                <div class="alert alert-danger">
                                    <strong>Cannot Delete!</strong><br>
                                    This remedy has been prescribed in <?php echo $prescriptionCount; ?> case(s).
                                    You must reassign or delete these cases first.
                                </div>
                                <a href="index.php" class="btn btn-secondary">Go Back</a>
                            <?php else: ?>
                                <form method="POST">
                                    <div class="mb-3">
                                        <label>Type <strong>DELETE</strong> to confirm:</label>
                                        <input type="text" name="confirm" class="form-control" placeholder="DELETE" required>
                                    </div>
                                    <button type="submit" class="btn btn-danger">
                                        <i class="fas fa-trash"></i> Permanently Delete
                                    </button>
                                    <a href="index.php" class="btn btn-secondary">Cancel</a>
                                </form>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>